美文网首页
python sftp工具

python sftp工具

作者: sarai_c7eb | 来源:发表于2019-08-05 13:41 被阅读0次

1 从远端server get files

#!/usr/bin/python
import os
from subprocess import *
fname='flist'    #need to change1:list the files need to be transferred
serv='xxx'       #need to change2:the server address;

f=open(fname)
lines=f.readlines()
sftp_shcmd='sftp %s'%serv
try:
  p=Popen(sftp_shcmd,shell=True,stdin=PIPE,stdout=PIPE,stderr=PIPE)
  
  print "---START---"
  print "the sftp transferring......"
  for idx in lines:
    ncmd="get "+idx
    p.stdin.write(ncmd)
  p.stdin.close()

  for line in p.stdout:
    if line="END\n":
      break;
    print line.strip()
  for line in p.stderr:
    if line="END\n":
      break;
    print line.strip()
except:
    print "---couldn't connect the server!!!---"

print "---END---"
  • 只使用1次Popen,然后用p.stdin.write(cmd)格式写入多个命令,最后用p.stdin.close()关闭shell。
  • 用两个for循环查看stdout结果。

2 run muticmd using Popen

from subprocess import Popen,PIPE,STDOUT
cmd1='echo "hello world"'
cmd2='ls -l'
final=Popen("{};{}".format(cmd1,cmd2),shell=True,stdout=PIPE,stderr=STDOUT,close_fds=True)
stdout,nothing=final.communicate()
log=open('log','w')
log.write(stdout)
log.close()

相关文章

网友评论

      本文标题:python sftp工具

      本文链接:https://www.haomeiwen.com/subject/wbnpdctx.html