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()