我可以通过Python脚本控制PSFTP吗? [英] Can i control PSFTP from a Python script?

查看:177
本文介绍了我可以通过Python脚本控制PSFTP吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Python脚本运行并控制PSFTP,以便将日志文件从UNIX框中移到Windows机器上。



我可以启动PSFTP并登录,但是当我尝试远程运行一个命令如'cd'时,它不能被PSFTP识别,并且只是在关闭PSFTP时在终端中运行。



我尝试运行的代码如下所示:

  import os 

os.system( < directory> -l< username> -pw< password>)
os.system(cd< anotherDirectory>)

我只是想知道这是否可行。或者如果在Python中有更好的方法来做到这一点。



谢谢。

解决方案

您需要将PSFTP作为子流程运行,并直接与流程对话。 os.system 每次调用时都会生成一个单独的子shell,因此它不能像按顺序将命令输入到命令提示符窗口中。查看标准Python 子流程模块的文档。你应该能够从那里完成你的目标。另外,还有一些可用的Python SSH软件包,例如 paramiko 扭曲。如果您已经对PSFTP感到满意,我肯定会坚持尽力让它工作。



子流程模块提示:

 #以下行生成psftp进程并将其标准输入
#绑定到p.stdin,并将其标准输出绑定到p.stdout
p = subprocess.Popen('psftp -l testuser -pw testpass'.split(),
stdin = subprocess.PIPE,stdout = subprocess.PIPE)
#将'cd some_directory'命令发送到进程就好像一个用户是
#在命令行输入它
p.stdin.write('cd some_directory \\\
')


i want to run and control PSFTP from a Python script in order to get log files from a UNIX box onto my Windows machine.

I can start up PSFTP and log in but when i try to run a command remotely such as 'cd' it isn't recognised by PSFTP and is just run in the terminal when i close PSFTP.

The code which i am trying to run is as follows:

import os

os.system("<directory> -l <username> -pw <password>" )
os.system("cd <anotherDirectory>")

i was just wondering if this is actually possible. Or if there is a better way to do this in Python.

Thanks.

解决方案

You'll need to run PSFTP as a subprocess and speak directly with the process. os.system spawns a separate subshell each time it's invoked so it doesn't work like typing commands sequentially into a command prompt window. Take a look at the documentation for the standard Python subprocess module. You should be able to accomplish your goal from there. Alternatively, there are a few Python SSH packages available such as paramiko and Twisted. If you're already happy with PSFTP, I'd definitely stick with trying to make it work first though.

Subprocess module hint:

# The following line spawns the psftp process and binds its standard input
# to p.stdin and its standard output to p.stdout
p = subprocess.Popen('psftp -l testuser -pw testpass'.split(), 
                     stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# Send the 'cd some_directory' command to the process as if a user were 
# typing it at the command line
p.stdin.write('cd some_directory\n')

这篇关于我可以通过Python脚本控制PSFTP吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆