下面是两种使用paramiko连接到linux服务器的代码
方式一:
ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect("某IP地址",22,"用户名", "口令")
上面的第二行代码的作用是允许连接不在know_hosts文件中的主机
方式二:
t = paramiko.Transport((“主机”,”端口”)) t.connect(username = “用户名”, password = “口令”)
如果连接远程主机需要提供密钥,上面第二行代码可改成:
t.connect(username = “用户名”, password = “口令”, hostkey=”密钥”)
例子:
#!/usr/bin/python import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect("某IP地址",22,"用户名", "口令") stdin, stdout, stderr = ssh.exec_command("你的命令")print stdout.readlines() ssh.close()
下载linux服务器上的文件
#!/usr/bin/python import paramiko t = paramiko.Transport((“主机”,”端口”)) t.connect(username = “用户名”, password = “口令”) sftp = paramiko.SFTPClient.from_transport(t) remotepath=’/var/log/system.log’ localpath=’/tmp/system.log’ sftp.get(remotepath, localpath) t.close()
上传文件到linux服务器
#!/usr/bin/python import paramiko t = paramiko.Transport((“主机”,”端口”)) t.connect(username = “用户名”, password = “口令”) sftp = paramiko.SFTPClient.from_transport(t) remotepath=’/var/log/system.log’ localpath=’/tmp/system.log’ sftp.put(localpath,remotepath) t.close()