1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import paramiko import paramiko server_ip = '192.168.1.1' server_user = 'root' server_passwd = '' server_port = 22 ssh = paramiko.SSHClient() def ssh_connect(): ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.load_system_host_keys() ssh.connect(server_ip, server_port,server_user, server_passwd) return ssh def client_connect(): client = paramiko.Transport((server_ip, server_port)) client.connect(username = server_user, password = server_passwd) return client def ssh_disconnect(client): client.close()
def exec_cmd(command, ssh): ''' windows客户端远程执行linux服务器上命令 ''' stdin, stdout, stderr = ssh.exec_command(command) err = stderr.readline() out = stdout.readline() print(stdout.read())
def win_to_linux(localpath, remotepath,client): ''' windows向linux服务器上传文件. localpath 为本地文件的绝对路径。如:D: est.py remotepath 为服务器端存放上传文件的绝对路径,而不是一个目录。如:/tmp/my_file.txt '''
sftp = paramiko.SFTPClient.from_transport(client) sftp.put(localpath,remotepath) client.close()
def linux_to_win(localpath, remotepath,client): ''' 从linux服务器下载文件到本地 localpath 为本地文件的绝对路径。如:D: est.py remotepath 为服务器端存放上传文件的绝对路径,而不是一个目录。如:/tmp/my_file.txt ''' sftp = paramiko.SFTPClient.from_transport(client) sftp.get(remotepath, localpath) client.close()
class AllowAllKeys(paramiko.MissingHostKeyPolicy): def missing_host_key(self, client, hostname, key): return
def muit_exec_cmd(ssh,cmd): ''' ssh ssh连接 cmd 多命名 ''' ssh.set_missing_host_key_policy(AllowAllKeys()) channel = ssh.invoke_shell() stdin = channel.makefile('wb') stdout = channel.makefile('rb')
stdin.write(cmd) print(stdout.read())
stdout.close() stdin.close()
cl = client_connect() sh = ssh_connect() muit_exec_cmd(sh,''' cd ~ ls sar exit ''') win_to_linux("t.txt","/data/t1.txt",cl) cl.close() sh.close()
|