【问题标题】:Pass Python variable inside command with Paramiko使用 Paramiko 在命令中传递 Python 变量
【发布时间】:2018-09-21 12:07:17
【问题描述】:

使用此命令,我想保存 sda 驱动器的 smartctl 命令的输出。

现在,由于我使用 RAID,我有多个驱动器,而不仅仅是 sda。

以下命令可以正常工作:

stdin, stdout, stderr = ssh.exec_command('/bin/su root -c "smartctl -a /dev/sda > /tmp/smartctl_output1"', get_pty=True) # ORIGINAL

我想实现我传递包含 sda、sdb、sdc 等的本地 Python 变量“DISK”而不是只传递静态值。

以下行产生错误:

stdin, stdout, stderr = ssh.exec_command('/bin/su root -c "smartctl -a /dev/" + DISK + " > /tmp/" + DISK', get_pty=True)

编辑:也试过了:

stdin, stdout, stderr = ssh.exec_command('/bin/su root -c "smartctl -a /dev/' + DISK + ' > /tmp/' + DISK, get_pty=True)
stdin.write(ROOTPASS)
stdin.write('\n')
DEBUG1=stdout.read()
print   "DEBUG COMMAND= " + DEBUG1

在 /tmp/ 中产生以下错误和文件 + 未创建磁盘:

DEBUG COMMAND= bash: -c: line 0: 寻找匹配的 `"' 时出现意外 EOF
bash:-c:第 1 行:语法错误:文件意外结束

【问题讨论】:

  • DISK是本地Python变量还是服务器上的环境变量?
  • DISK 是局部变量

标签: python python-2.7 ssh paramiko


【解决方案1】:

你的问题与帕拉米科无关。

这只是 Python 中字符串的简单串联:

ssh.exec_command(
     '/bin/su root -c "smartctl -a /dev/' + DISK + ' > /tmp/' + DISK + '"',
     get_pty=True)

如需更好的选择,请参阅How to insert string into a string as a variable?

【讨论】:

  • 感谢您的回答,尝试了包括您在内的数十种报价组合,似乎不起作用。我已经更新了问题。
  • 啊,经过你的编辑,它就像我想要的那样工作,非常感谢@martin-prikryl
猜你喜欢
  • 2019-12-23
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 2012-11-20
相关资源
最近更新 更多