首页 > 代码库 > python模块paramiko的上传下载和远程执行命令
python模块paramiko的上传下载和远程执行命令
#!/usr/bin/python # -*- coding: utf-8 -*- import paramiko,os,datetime server_ip = ‘192.168.1.123‘ server_user = ‘root‘ server_passwd = ‘10241010‘ server_port = 22 #local_dir=‘C:\Python27‘ #remote_dir=‘/soft2/nba/‘ def ssh_connect(): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(server_ip, server_port,server_user, server_passwd) return ssh def ssh_disconnect(client): client.close() def exec_cmd(command): ‘‘‘ paramiko功能1 windows客户端远程执行linux服务器上命令: ‘‘‘ ssh = ssh_connect() stdin, stdout, stderr = ssh.exec_command(command) err = stderr.readline() out = stdout.read() if "" != err: print "command: " + command + " exec failed!\nERROR :" + err return true, err else: print "command: " + command + " exec success." print out, def win_to_linux(local_dir, remote_dir): ‘‘‘ paramiko功能2 windows向linux服务器上传(下载)文件: ‘‘‘ try: client = paramiko.Transport((server_ip, server_port)) client.connect(username = server_user, password = server_passwd) sftp = paramiko.SFTPClient.from_transport(client) #files = sftp.listdir(remote_dir) #下载 files = os.listdir(local_dir) #上传 for f in files: #print ‘‘ print ‘-----------------------‘ print ‘Beginning to upload file to %s %s‘%(server_ip,datetime.datetime.now()) print ‘Uploading file-->‘,os.path.join(local_dir,f) #sftp.get(os.path.join(remote_dir,f),os.path.join(local_dir,f)) #下载 sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f)) #上传 print ‘Uploading file success.‘ #print ‘-----------------------‘ client.close() except Exception,err_info: print err_info print exec_cmd.__doc__ exec_cmd(‘df -h‘) print ‘‘ print win_to_linux.__doc__.strip() win_to_linux(‘D:\show‘,‘/soft2/nba/‘)
执行结果:
paramiko功能1 windows客户端远程执行linux服务器上命令: command: df -h exec success. Filesystem Size Used Avail Use% Mounted on /dev/sda2 8.5G 8.4G 0 100% / /dev/sda1 289M 34M 241M 13% /boot tmpfs 506M 0 506M 0% /dev/shm paramiko功能2 windows向linux服务器上传(下载)文件: ----------------------- Beginning to upload file to 192.168.1.123 2014-05-16 17:26:56.899000 Uploading file--> D:\show\lisa.txt Uploading file success. ----------------------- Beginning to upload file to 192.168.1.123 2014-05-16 17:26:56.939000 Uploading file--> D:\show\prada.txt Uploading file success.
http://www.lag.net/paramiko/docs/ paramiko文档
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。