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.   
  4. ssh = paramiko.SSHClient() 
  5. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
  6. ssh.connect(" IP ",22," ", " ") 
  7. stdin, stdout, stderr = ssh.exec_command(" ") 
  8. print stdout.readlines() 
  9. 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.   
  4. t = paramiko.Transport((“ ”,” ”)) 
  5. t.connect(username = “ ”, password = “ ”) 
  6. sftp = paramiko.SFTPClient.from_transport(t) 
  7. remotepath=’/var/log/system.log’ 
  8. localpath=’/tmp/system.log’ 
  9. sftp.get(remotepath, localpath) 
  10. t.close() 

 
4.Realize upload file
 

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