linux - Python 脚本不发送 linux 命令。我使用 Paramiko 进行远程 SSH 连接

标签 linux ssh paramiko python-3.6

import paramiko
import time
import os


ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('server',port=22,username='user',password='pass123')
print("connected to the linux machine from windows machine.")

channel=ssh.invoke_shell()

channel_data = str()

while True:
    if channel.recv_ready():
        channel_data += channel.recv(9999).decode(encoding='utf_8', errors='strict')
        os.system('cls')
        print("##### Device Output #####")
        print("\n",channel_data)
        print("\n #####################")
    else:
        continue

    time.sleep(5)

    if channel_data.endswith('[root@home ~]#'):
        #if block statements are not executed why
        print("Hi,why not executing this statement")
        ssh.send('cd /\n')
        #stdin,stdout,stderr=ssh.exec_command('pwd')
        #output1=stdout.readlines()
        print("My present working directory is")
    elif channel_data.endswith('[root@home /]#'):
        #Also elif block statements are not executed why
        ssh.send('mkdir BB444')
        #stdin,stdout,stderr=ssh.exec_command('mkdir /pn444')
        #output1=stdout.readlines()
        print("created pn444 directory")

我正在使用 paramiko 进行 ssh 连接。我能够登录到 linux 机器。然后我正在检查条件,即如果 channel_data.endswith('[root@home ~]#') 然后发送“cd/”命令 else if channel_data.endswith('[root@home/]#') 然后发送'mkdir BB444 ' 命令,但此脚本未发送这些命令。调试后我看到这些发送命令语句没有执行。请让我知道我在这里犯了什么错误。

我正在使用 python 3.6,paramiko 2.1.1

最佳答案

问题可能不是 python 脚本。我在从 python 脚本向 putty ssh 连接发送远程命令时遇到了类似的问题。如果您在公司网络中。一些管理员从我用于 putty 的 -m 等参数中删除命令。这样您就可以登录,但是当您尝试发送远程命令时。它没有到达服务器。如果您在公司网络中,请咨询您的管理员以了解 ssh 连接的远程命令。

关于linux - Python 脚本不发送 linux 命令。我使用 Paramiko 进行远程 SSH 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42219776/

相关文章:

python - 在 linux 中执行远程命令时如何处理错误

python - Paramiko 仅连接到 IP 地址而不是 Python 中的主机名?

java - 在shell脚本中调用Java程序无法运行hadoop命令

linux - 在 ubuntu 上安装 Postgresql 12 失败 - apt update 有错误

linux - alloc_pages() 与 __free_pages() 配对

linux - tsocks 不隧道到 ssh

git - Windows 真的只是自发地为 git 重新生成了我的 ssh key 吗?

go - gCloud 实例 : ssh: handshake failed: ssh: unable to authenticate, 尝试的方法 [无公钥],没有支持的方法

python ,Paramiko : How to do a "ssh -n user@host cmd" using paramiko?

python - 将 python 守护程序公开为服务