Paramiko is a module written in the Python language that follows the SSH2 protocol and supports the connection of remote servers in a way that is encrypted and authenticated.
Python's Paramiko module makes it easy to implement SSH logins and execute commands.
1. Paramiko Module Installation 1.1 Install Pycrypto Library
Please poke here: http://download.csdn.net/detail/oatnehc/8825715;
The home page of the Pycrypto library is here: https://www.dlitz.net/software/pycrypto/
Pycrypto Library Installation Method
python setup.py build && python setup.py install
1.2 Installing Paramiko
paramiko:http://download.csdn.net/detail/oatnehc/8825743
The home page of the Paramiko library is here: Https://pypi.python.org/pypi/paramiko
The installation method of the Paramiko library is super simple.
python setup.py build && python setup.py install
2. Simply use 2.1 to execute a remote command
#!/usr/bin/python import paramiko ssh = Paramiko.set_missing_host_key_policy (Paramiko .connect ( "One IP address", 22," user name ", " password ") stdin, stdout, stderr = Ssh.exec_command ( "your command") print stdout .readlines () ssh.close ()
2.2 Uploading files to remote
#!/usr/bin/python import paramiko t = paramiko.Transport(("某IP地址",22)) t.connect(username = "用户名", password = "口令") sftp = paramiko.SFTPClient.from_transport(t) remotepath=‘/tmp/test.txt‘ localpath=‘/tmp/test.txt‘ sftp.put(localpath,remotepath) t.close()
2.3 Uploading files to remote
#!/usr/bin/python import paramiko t = paramiko.Transport(("某IP地址",22)) t.connect(username = "用户名", password = "口令") sftp = paramiko.SFTPClient.from_transport(t) remotepath=‘/tmp/test.txt‘ localpath=‘/tmp/test.txt‘ sftp.get(remotepath, localpath) t.close()
3. Advanced usage
It is often necessary to manage multiple servers or virtual machines, which can be done in a batch manner.
#-*-Coding:utf-8-*-#!/usr/bin/pythonImport ParamikoImport threadingDefSsh2(ip,username,passwd,cmd):Try:ssh = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect (IP,22,username,passwd,timeout=5)For MIn Cmd:stdin, stdout, stderr = Ssh.exec_command (m) out = Stdout.readlines ()For OIn-out:Print O,#屏幕输出Print '%s\tok\n '% (IP) ssh.close () except: print '%s\terror\n '% (IP) if __ Name__== ' __main__ ': cmd = [ ' echo hello! '] #需要执行的命令列表 username = "root" #用户名 passwd = "root" #密码 threads = [] #多线程 print "Begin Excute ..." for i in range (1,254): IP = ' 192.168.1. ' +str (i) a=threading. Thread (target=ssh2,args= (Ip,username,passwd,cmd)) A.start ()
Reference
Http://www.cnblogs.com/xia520pi/p/3805043.html
Http://www.oschina.net/p/paramiko
Http://developer.51cto.com/art/201206/340118.htm
Login to SSH using Python's Paramiko module