在 python ssh 中无法获得任何输出

not able to get anything in output in python ssh

我正在尝试连接到远程服务器,然后尝试登录该机器中的 sql 服务器。但是我没有得到这个脚本的任何输出

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy() )
ssh.connect(hostname='172.18.109.244', username='bgf', password='bgf')
print "Logged In to EMS"
cmd = 'mysql -uroot -root'

stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write("show databases;")
stdin.write('\n')
stdin.flush()
print stdout.read()

正如@Charles 在评论中提到的,

read() consumes content to EOF. There is no EOF here because MySQL is still open. The easy answer is to not just flush stdin, but close it.

你不能那样做,因为 MySQL 仍然打开,你的脚本会挂在那里。因此,如果您只想获取数据库,则将查询传递给 MySQL 连接即可正常工作:)。

    import paramiko
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy() )
    ssh.connect(hostname='172.18.109.244', username='somuser',password='bgf')
    print "Logged In to EMS"
    cmd = 'mysql -h somehost.example.com -uroot -proot -e \'show databases;\''

    stdin, stdout, stderr = ssh.exec_command(cmd)
    # stdin.write("show databases;")
    stdin.write('\n')
    stdin.flush()
    print stdout.read()