1,SSH Login command Line implementation:
#!/usr/bin/env python# encoding:utf-8import paramikoprivate_key_path = '/users/aolens/.ssh/id_rsa ' key = Paramiko. Rsakey.from_private_key_file (private_key_path) ssh = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) ssh.connect (' 192.168.1.201 ', 22,username= ' root ', Pkey=key) #ssh. Connect (' 192.168.1.201 ', $, ' root ' , ' aolens ') #不采用迷药登陆时flag = Truewhile flag: con = raw_input (' Enter the command to execute: ') if con = = ' quit ': flag = falsessh.close () E LSE: stdin, stdout, stderr = Ssh.exec_command (con) print stdout.read ()
2, File upload download
t = Paramiko. Transport (' 192.168.1.201 ', ()) T.connect (username= ' root ', password= ' qixiang123 ') sftp = Paramiko. Sftpclient.from_transport (t) #sftp. Put ('/users/aolens/downloads/1.sh ', '/root/1.sh ') #put上传文件到服务器, the front is the upload file address, Behind is the post-upload file address sftp.get ('/root/1.sh ', '/users/aolens/downloads/2.sh ') #get下载文件, Front is, behind is downloaded after the storage address t.close ()
Combine SSH login to optimize file upload and download
#!/usr/bin/env python# encoding:utf-8import paramikoprivate_key_path = '/users/aolens/.ssh/id_rsa ' key = Paramiko. Rsakey.from_private_key_file (private_key_path) t = Paramiko. Transport (' 192.168.1.201 ', ()) T.connect (username= ' root ', pkey=key) sftp = Paramiko. Sftpclient.from_transport (t) flag = Truewhile Flag:con = raw_input (' Enter the command to execute: ') if con = = ' quit ': flag = Falset. Close () elif con = = ' put ': Com_add = raw_input (' Input file Source address: ') Target_add = raw_input (' Input file storage address: ') SFTP.P UT (com_add,target_add) print ' upload complete [=========================] 100% ', "file uploaded to:%s"% (target_add) elif con = = ' Get ': Co M_add = raw_input (' Input file Source address: ') Target_add = raw_input (' Input file storage address: ') sftp.get (com_add,target_add) print ' Download complete [= ========================] 100% ', "File stored in:%s"% (target_add) else:print ' input correct upload download command ' print ' upload: put ' print ' Download: Get ' print ' ========================= '
upper SSH login optimization, output information
#!/usr/bin/env python# encoding:utf-8import paramikoprivate_key_path = '/users/aolens/.ssh/id_rsa ' key = Paramiko. Rsakey.from_private_key_file (private_key_path) ssh = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) ssh.connect (' 192.168.1.201 ', 22,username= ' root ', Pkey=key) #ssh. Connect (' 192.168.1.201 ', $, ' root ' , ' aolens ') #不采用迷药登陆时flag = Truewhile flag: con = raw_input (' \033[1;34m Enter the command to execute: \033[0m ') if con = = ' quit ': Flag = False ssh.close () else: stdin, stdout, stderr = Ssh.exec_command (con) for I In (Stdout.read (), Stderr.read ()):p rint I
SSH login using Paramiko, file upload and download