python - 使用 Paramiko 在命令内传递 Python 变量

标签 python python-2.7 ssh paramiko

通过此命令,我想保存 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/中的文件未创建 + DISK:

DEBUG COMMAND= bash: -c: line 0: unexpected EOF while looking for matching `"'
bash: -c: line 1: syntax error: unexpected end of file

最佳答案

您的问题与Paramiko无关。

这只是 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?

关于python - 使用 Paramiko 在命令内传递 Python 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49777888/

相关文章:

python 多处理: processes don't work

python - 更快地比较两个列表

python - Django based on PostGreSql error while executing python manage.py runserver- "raise ImproperlyConfigured("Error loading psycopg2 module : %s"% e)"

python - 正则表达式匹配所有非字母,不包括变音符号(python)

python - 创建套接字时"[Errno 1] Operation not permitted"

linux - 通过 ssh 连接使用命令 sed 和 echo

python - 编辑 scikit-learn 决策树

Python编码/解码问题

Git SSH 设置权限被拒绝(公钥)

linux - 如何通过现有的 SSH 连接使用 OSX Coda 到 SFTP?