在远程Windows客户端上执行python脚本

时间:2017-12-12 09:10:04

标签: python windows python-2.7 ssh paramiko

我使用paramiko在远程Windows服务器上执行命令。我能够执行dir之类的命令并提取输出,但执行python脚本似乎失败了。不会抛出任何错误消息。

这是我的代码段:

def ssh_connect(ip,user,pwd):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, username=user, password=pwd)
        return ssh


def execute_command(device_details, command):
       ip = device_details.get('ip')
       username = device_details.get('username')
       password = device_details.get('password')
       ssh_ns_obj = ssh_connect(ip, username, password)
       ssh_stdin, ssh_stdout, ssh_stderr = ssh_ns_obj.exec_command(command)
       print ssh_stderr.read()
       return ssh_stdout.read()

device_details = dict()
device_details['ip'] = 'a.b.c.d'
device_details['username'] = 'Administrator'
device_details['password'] = 'pass'

command_1 = "cmd /c mkdir asdf"
output = execute_command(device_details, command_1)

command_2 = 'cmd /c "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe C:\pythonattempt\try.py"'
output = execute_command(device_details, command_2)

以下是try.py中提及的command_2

import os

if __name__ == '__main__':
    print ("Hey, just starting")

    os.system(r"mkdir C:\Users\Administrator\Desktop\x")
    print ("hey, file is up")

    with open(r"C:\Users\Administrator\Desktop\x.txt", "w") as f:
        f.write("This is a line of a file")

command_1成功执行,我能够看到在我的Windows机器上创建的目录。但是command_2不会抛出任何错误,但也不会被执行。

我知道,因为x.txt或文件夹x未创建。

我在Windows上安装了freeSSHd服务。我能够ssh进入我的Windows机器并执行完全相同的命令,并且它正在工作。

见下图:

enter image description here

我如何进行?

1 个答案:

答案 0 :(得分:0)

错误是\t是一个特殊字符,当我尝试执行C:\pythonattempt\try.py时,\t被视为特殊字符。

我意识到当我在sublime而不是vi上打开相同的脚本时,颜色有所不同!