在pexpect脚本中使用scp时出错

时间:2014-03-18 12:08:05

标签: python scp pexpect

我试图制作一个从xml文件读取数据并制作备份文件副本的备份收费 xml文件包含所有设备数据,如:

<data>
    <devices>
        <device name='cisco' ip='10.10.10.10' uname='username' password='passpass' backup_make='Write memory' backup_location_device='nvram:/startup-config' backup_location='idan/backup_fiels/backup1.cfg' ></device>     
        </devices>
</data> 

我使用数据连接在ssh中,就像这样,它的工作正常:

xmldoc = minidom.parse('xmlfile.xml')
devicelist = xmldoc.getElementsByTagName('device')

    address=('ssh ',devicelist[0].attributes['uname'].value,'@',devicelist[0].attributes['ip'].value)
    password = (devicelist[0].attributes['password'].value)

    ssh_device = pexpect.spawn(address)
    ssh_device.expect('.assword:')
    .
    .
    .

但是当我为scp发现错误时也是如此

backup = ('scp ',devicelist[0].attributes['uname'].value,'@',devicelist[0].attributes['ip'].value,':',devicelist[0].attributes['backup_location_device'].value,' test.cfg')

ssh_device = pexpect.spawn(backup)
ssh_device.expect('.assword:')
.
.
.

当我运行脚本时:

Traceback (most recent call last):
  File "xmltest.py", line 34, in <module>
    backup_make = pexpect.spawn(backup)
  File "/usr/local/lib/python2.7/site-packages/pexpect/__init__.py", line 485, in __init__
    self._spawn(command, args)
  File "/usr/local/lib/python2.7/site-packages/pexpect/__init__.py", line 590, in _spawn
    'executable: %s.' % self.command)
pexpect.ExceptionPexpect: The command was not found or was not executable: scp Netadmn9@10.10.10.10:nvram:/startup-config test.cfg.

并且floowing命令也正常工作:

backup = ('scp Netadmn9@10.106.11.111:nvram:/startup-config HSBU1a1_idan.cfg')

ssh_device = pexpect.spawn(backup)
ssh_device.expect('.assword:')
.
.
.

任何人都可以帮忙吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

Pexpect期待一个命令,然后是一个参数列表,所以它需要分解。

尝试:

backup = "scp %s@%s:%s test.cfg" % (devicelist[0].attributes['uname'].value,devicelist[0].attributes['ip'].value,devicelist[0].attributes['backup_location_device'].value)

split_command = shlex.split(backup)
ssh_device = pexpect.spawn(split_command)

另外,如果您设置公共私钥登录,那么您不需要pexpect进行备份就可以使用子进程调用。

阅读here

split_command = shlex.split(backup)
subprocess.call(split_command)

我添加了一个字符串格式行,而不是你生成的元组。

这应该通过shlex.split()

明智地分开