1,SSh登陆命令行实现:
#!/usr/bin/env python # encoding: utf-8 import paramiko private_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‘, 22,‘root‘,‘aolens‘) #不采用迷药登陆时 flag = True while flag: con = raw_input(‘输入要执行的命令: ‘) if con == ‘quit‘: flag = False ssh.close() else: stdin, stdout, stderr = ssh.exec_command(con) print stdout.read()
2,实现文件上传下载
t = paramiko.Transport((‘192.168.1.201‘,22)) t.connect(username=‘root‘,password=‘qixiang123‘) sftp = paramiko.SFTPClient.from_transport(t) #sftp.put(‘/Users/aolens/Downloads/1.sh‘,‘/root/1.sh‘) #put上传文件到服务器,前边是上传文件地址,后边是上传后文件地址 sftp.get(‘/root/1.sh‘,‘/Users/aolens/Downloads/2.sh‘) #get下载文件,前边是下载地址,后边是下载后存放地址 t.close()
结合SSH登陆,优化文件上传下载
#!/usr/bin/env python # encoding: utf-8 import paramiko private_key_path = ‘/Users/aolens/.ssh/id_rsa‘ key = paramiko.RSAKey.from_private_key_file(private_key_path) t = paramiko.Transport((‘192.168.1.201‘,22)) t.connect(username=‘root‘,pkey=key) sftp = paramiko.SFTPClient.from_transport(t) flag = True while flag: con = raw_input(‘输入要执行的命令: ‘) if con == ‘quit‘: flag = False t.close() elif con == ‘put‘: com_add = raw_input(‘输入文件来源地址:‘) target_add = raw_input(‘输入文件存放地址:‘) sftp.put(com_add,target_add) print ‘上传完成[=========================] 100% ‘, "文件上传至:%s"% (target_add) elif con == ‘get‘: com_add = raw_input(‘输入文件来源地址:‘) target_add = raw_input(‘输入文件存放地址:‘) sftp.get(com_add,target_add) print ‘下载完成[=========================] 100% ‘, "文件存放在:%s"% (target_add) else: print ‘输入正确的上传下载指令‘ print ‘上传: put ‘ print ‘下载: get ‘ print ‘=========================‘
对上边SSH登陆优化,输出信息
#!/usr/bin/env python # encoding: utf-8 import paramiko private_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‘, 22,‘root‘,‘aolens‘) #不采用迷药登陆时 flag = True while flag: con = raw_input(‘\033[1;34m输入要执行的命令: \033[0m‘) if con == ‘quit‘: flag = False ssh.close() else: stdin, stdout, stderr = ssh.exec_command(con) for i in (stdout.read(),stderr.read()): print i
本文出自 “aolens·程超” 博客,请务必保留此出处http://aolens.blog.51cto.com/7021142/1847499
原文地址:http://aolens.blog.51cto.com/7021142/1847499