import sys
import os
def main():
print os.name
if __name__ == '__main__':
try:
if sys.argv[1] == 'deploy':
import paramiko
# Connect to remote host
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('remote_hostname_or_IP', username='john', password='secret')
# Setup sftp connection and transmit this script
sftp = client.open_sftp()
sftp.put(__file__, '/tmp/myscript.py')
sftp.close()
# Run the transmitted script remotely without args and show its output.
# SSHClient.exec_command() returns the tuple (stdin,stdout,stderr)
stdout = client.exec_command('python /tmp/myscript.py')[1]
for line in stdout:
# Process each line in the remote output
print line
client.close()
sys.exit(0)
except IndexError:
pass
# No cmd-line args provided, run script normally
main()
可以使用ssh。Python接受连字符(-)作为参数来执行标准输入
有关详细信息,请运行python--help。
因为
cat |
通常不需要虽然这个问题不是很新,而且已经选择了答案,但我想分享另一个不错的方法。
使用paramiko库(SSH2的纯python实现),python脚本可以通过SSH连接到远程主机,复制自身(!)到该主机,然后在远程主机上执行该副本。远程进程的Stdin、stdout和stderr将在本地运行脚本中可用。所以这个解决方案与IDE几乎是独立的。
在本地计算机上,我使用命令行参数'deploy'运行脚本,该参数触发远程执行。如果没有这样的参数,将运行用于远程主机的实际代码。
为了简化这个例子,省略了异常处理。在具有多个脚本文件的项目中,可能需要将所有这些文件(以及其他依赖项)放在远程主机上。
相关问题 更多 >
编程相关推荐