1

我有一个 python 脚本,它应该 ssh 到客户端并从客户端执行 bash。作为测试场景,我只使用一台机器进行连接,但目标是连接到多个客户端并从这些机器执行 bash 脚本。

我的 Python 代码:

 import os 
 import subprocess
 import time


def ssh_login_execute():
    if device['PWD'] != "":
            run=('sshpass -p %s ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -t -p %s %s@%s' % (device['PWD'], device['PORT'], device['USER'], device['IP']))
    else:
            run=('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -t -p %s %s@%s' % (device['PORT'], device['USER'], device['IP']))

    cmd = ('cd %s' % (script_path))

    run2=run.split()
    run2.append(cmd)
    t=subprocess.Popen(run2, stdout=subprocess.PIPE, stderr=open(os.devnull, 'w'))
    print "I am in 192.168.1.97"
    execute_tg()
    return t

def execute_tg():
   path = "/home/"
   os.chdir(path)
   print os.getcwd()
   cmd=("sh my_script.sh")
   t=subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

if __name__ == "__main__":
    device = {}
    device['PORT']=22
    device['PWD']= "abcd"
    device['USER']= "root"
    device['IP']= "192.168.1.97"
    script_path= "/home/"
    ssh_login_execute()

在运行代码“python script.py”时,我看到输出为:

  I am in 192.168.1.97
  /home/
  Output is sh: 0: Can't open my_script.sh

虽然“my_script.sh”位于 192.168.1.97 的 /home 目录中。我如何摆脱这个问题,同时使其可扩展为 ssh 到多个客户端并执行 bash。

4

4 回答 4

2

您的脚本my_script.sh可能/home/与代码中的预期不同。

   path = "/home/"
   os.chdir(path)
   print os.getcwd()
   cmd=("sh my_script.sh")

它也应该打印当前目录以及print os.getcwd(). 您应该根据脚本的实际位置更改这些值。

于 2013-09-19T17:48:12.677 回答
1

这是一个使用 paramiko 模块和 getpass 模块的示例:

#!/usr/bin/python
import paramiko
import getpass
class Remote():
    def __init__(self, hostfile, username, commands):
        self.hostfile = hostfile
        self.username = username
        self.commands = commands
    def execute(self):
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        ##########################################################
        # just in case it does not recognize the known_host keys
        # in the known_hosts file
        ##########################################################
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.password = getpass.getpass("Password: ")
        for i in self.hostfile.readlines():
            print("Connecting to..." + i)
            client.connect(i.strip(), 22, self.username, self.password)
            stdin, stdout, stderr = client.exec_command(self.commands)
            for t in stdout.readlines():
                print(t.strip())
            for t in stderr.readlines():
                print(t.strip())
#--------------------------------------------------------
commands="""
echo "##################################################";
hostname;
echo "##################################################";
uname -a;
echo "##################################################";
dmidecode -t bios
"""
#---------------------------------------------------------
username = raw_input("Username: ")
hostfile = open('hosts')
a = Remote(hostfile, username, commands)
a.execute()
于 2013-09-19T22:31:27.403 回答
0

您的“主”目录通常类似于/home/<username>或可能是/users/<username>. 一般来说,shell 通常会接受~作为主目录路径的同义词。这是否可行:

cmd=("sh ~/my_script.sh")
于 2013-09-19T17:52:28.670 回答
0

实际上 sshpass 一次执行 ssh 命令/连接。一旦通过 subprocess.Popen() 执行远程查询,您的程序控制将在下一行返回到本地计算机。并且您的程序将给出错误“无法打开 my_script.sh”,因为您的脚本不在本地计算机上,而在远程计算机上。

我的建议是使用在单个程序变量中执行的内容(在您的情况下为“run2”变量)制作完整的 sshpass 命令,然后一次性将其传递给 subprocess.Popen()。修改后的代码如下:

import os 
import subprocess
import time

def ssh_login_execute():
    if device['PWD'] != "":
        run=('sshpass -p %s ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -t -p %s %s@%s' % (device['PWD'], device['PORT'], device['USER'], device['IP']))
    else:
        run=('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -t -p %s %s@%s' % (device['PORT'], device['USER'], device['IP']))

    cmd = ('sh /%s/%s' % (script_path,'my_script.sh'))

    run2=run.split()
    run2.append(cmd)
    t=subprocess.Popen(run2, stdout=subprocess.PIPE, stderr=open(os.devnull, 'w'))
    print "I am in 192.168.1.97" # HERE YOU ASSUMED THAT YOU ARE IN REMOTE MACHINE BUT ACTUALLY YOU ARE IN LOCAL MACHINE ONLY
    return t

if __name__ == "__main__":
    device = {}
    device['PORT']=22
    device['PWD']= "abcd"
    device['USER']= "root"
    device['IP']= "192.168.1.97"
    script_path= "/home/"
    ssh_login_execute()
于 2015-09-23T10:30:24.313 回答