在python中使用sshpass的ssh似乎不起作用

时间:2013-09-19 17:40:15

标签: python linux bash shell ssh

我有一个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目录中。 如何摆脱这个问题,同时使其可以扩展到多个客户端并执行bash。

4 个答案:

答案 0 :(得分:2)

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

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

此外,它还应该使用print os.getcwd()打印当前目录。您应该根据脚本的实际位置更改这些值。

答案 1 :(得分: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()

答案 2 :(得分:0)

您的“主页”目录通常类似于/home/<username>/users/<username>。通常,shell通常会接受~作为主目录路径的同义词。这是否有效:

cmd=("sh ~/my_script.sh")

答案 3 :(得分:0)

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

我的建议是使用单个程序varibale(在你的'run2'变量中)执行什么来执行完整的sshpass命令,并在单个go中将它传递给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()