天天看点

PYTHON:如何使用paramiko远程操作

1.Paramiko is a python's modules for link remote server.The following two methods are about how to use Paramiko link remote servers

The first method

  1. ssh = paramiko.SSHClient() 
  2. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
  3. ssh.connect("某IP地址",22,"用户名", "口令") 

The second line code useage allow connecting unknow hosts in know-hosts file in above.

2.Example,Next code show the function about login server and excute a command and print into client.

  1. #!/usr/bin/python  
  2. import paramiko 
  3. ssh = paramiko.SSHClient() 
  4. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
  5. ssh.connect("某IP地址",22,"用户名", "口令") 
  6. stdin, stdout, stderr = ssh.exec_command("你的命令") 
  7. print stdout.readlines() 
  8. ssh.close() 

The usual command:

df:查看磁盘使用情况
uptime:显示系统运行时间信息
cat:显示某文件内容
mv/cp/mkdir/rmdir:对文件或目录进行操作
/sbin/service/ xxxservice start/stop/restart:启动、停止、重启某服务
netstat -ntl |grep 8080:查看8080端口的使用情况 
 或者 nc -zv localhost :查看所有端口的使用情况 
find / -name XXX:查找某文件      
...      

So we nearly do nothing face to more servers if you use the python code  

3.Realize download file 

  1. #!/usr/bin/python  
  2. import paramiko 
  3. t = paramiko.Transport((“主机”,”端口”)) 
  4. t.connect(username = “用户名”, password = “口令”) 
  5. sftp = paramiko.SFTPClient.from_transport(t) 
  6. remotepath=’/var/log/system.log’ 
  7. localpath=’/tmp/system.log’ 
  8. sftp.get(remotepath, localpath) 
  9. t.close() 

4.Realize upload file

  1. #!/usr/bin/python  
  2. import paramiko 
  3. t = paramiko.Transport((“主机”,”端口”)) 
  4. t.connect(username = “用户名”, password = “口令”) 
  5. sftp = paramiko.SFTPClient.from_transport(t) 
  6. remotepath=’/var/log/system.log’ 
  7. localpath=’/tmp/system.log’ 
  8. sftp.put(localpath,remotepath) 
  9. t.close() 

转载于:https://blog.51cto.com/mianhuhu/1185914