我对Python和编程很陌生。我正试图通过python脚本在两台计算机之间复制一个文件。但是代码
os.system("ssh " + hostname + " scp " + filepath + " " + user + "@" + localhost + ":" cwd)
不会起作用的。我认为它需要一个密码,如How to copy a file to a remote server in Python using SCP or SSH?所述。我没有得到任何错误日志,文件只是不会显示在我当前的工作目录。
但是,使用os.system("ssh " + hostname + "command")
或os.popen("ssh " + hostname + "command")
的其他命令都可以工作。->;command = e.g. ls
当我试着
ssh hostname scp file user@local:directory
在命令行中,它不需要输入密码就可以工作。
我尝试将os.popen
命令与getpass和pxsh模块结合起来,建立到远程服务器的ssh连接,并使用它直接发送命令(我只测试了一个简单的命令):
import pxssh
import getpass
ssh = pxssh.pxssh()
ssh.force_password = True
hostname = raw_input("Hostname: ")
user = raw_input("Username: ")
password = getpass.getpass("Password: ")
ssh.login(hostname, user, password)
test = os.popen("hostname")
print test
但是我无法将命令传递到远程服务器(print test
显示hostname=local而不是远程服务器),但是我确信,连接已经建立。我认为建立连接比总是在bash命令中使用"ssh " + hostname
更容易。我也尝试了How to copy a file to a remote server in Python using SCP or SSH?中的一些解决方法,但我必须承认,由于缺乏有效期,我没有让他们工作。
非常感谢你帮助我。
我认为最简单(避免输入密码)和最安全的方法是首先设置public/private key authentication。完成后,您可以通过执行
ssh user@hostname
登录到远程系统,下面的bash命令将完成此操作:相应的Python代码是:
相关问题 更多 >
编程相关推荐