2012-01-09 529 views
4
def execute(self,command): 
      to_exec = self.transport.open_session() 
      to_exec.exec_command(command) 
      print 'Command executed' 
connection.execute("install.sh") 

当我检查远程系统时,发现脚本没有运行。任何线索?如何在python中使用ssh远程执行脚本?

+0

更多的代码,请。没有足够的背景。 – 2012-01-09 01:29:19

+0

问题太模糊了,你使用了哪个ssh包装,错误是什么,你怎么知道“脚本没有运行”而不是“脚本运行但是有错误”。 – 2012-01-09 01:33:39

+1

我不知道你为什么要这样做,但如果是用于sys管理,你可能会发现[Fabric](http://fabfile.org/)有用。 – charlax 2012-01-09 03:14:25

回答

-2
subprocess.Popen('ssh thehost install.sh') 

查看subprocess模块。

+0

,并确保你有ssh密钥的生成,否则你的程序将无法从cron执行时询问密码。 – 2012-01-09 01:57:18

+1

最好使用[ssh module](http://pypi.python.org/pypi/ssh/1.7.11),它旨在使其强大且易于使用SSH协议;没有充分的理由使用'subprocess'模块,因为它不仅更加麻烦,而且你也不能依赖'ssh'的返回码,因为如果它返回错误码255,你不能确定这是你的远程脚本返回,或者如果这只是'ssh'由于与远程脚本完全无关的错误而返回代码。 – aculich 2012-01-10 03:46:02

11

下面的代码会做你想要什么,你可以使其适应你的execute功能:

from paramiko import SSHClient 
host="hostname" 
user="username" 
client = SSHClient() 
client.load_system_host_keys() 
client.connect(host, username=user) 
stdin, stdout, stderr = client.exec_command('./install.sh') 
print "stderr: ", stderr.readlines() 
print "pwd: ", stdout.readlines() 

注意,虽然,命令将默认为您$HOME目录,所以你要么需要有install.sh在您的$PATH或(很可能)您需要cd到包含install.sh脚本的目录。

您可以检查您的默认路径:

stdin, stdout, stderr = client.exec_command('getconf PATH') 
print "PATH: ", stdout.readlines() 

但是,如果它不是在你的路径,你可以cd并执行这样的脚本:如果脚本不

stdin, stdout, stderr = client.exec_command('(cd /path/to/files; ./install.sh)') 
print "stderr: ", stderr.readlines() 
print "pwd: ", stdout.readlines() 

在您的$PATH中,您需要使用./install.sh而不是install.sh,就像您在命令行中一样。

如果您仍然有一切后,以上问题也可能是件好事,检查install.sh文件的权限,太:

stdin, stdout, stderr = client.exec_command('ls -la install.sh') 
print "permissions: ", stdout.readlines() 
相关问题