Paramiko 的 invoke_shell() 方法怎么读取输出
时间: 2023-06-05 18:07:46 浏览: 852
invoke_shell() 方法可以通过 send() 方法向远程服务器发送命令,并通过 recv() 方法获取远程服务器返回的结果。具体实现可以参考以下代码:
```
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='example.com', username='user', password='pass')
shell = client.invoke_shell()
shell.send('ls -l\n')
while not shell.recv_ready():
pass
output = shell.recv(1024)
print(output)
```
上述代码连接到远程服务器 example.com ,使用用户名为 user ,密码为 pass ,然后执行 ls -l 命令并读取结果。其中 shell.send() 方法用于发送命令,shell.recv() 方法用于获取输出结果。
相关问题
python paramiko invoke_shell
`paramiko` 是一个 Python 的 SSH 库,可以用来连接远程服务器并执行命令。`invoke_shell` 方法可以打开一个交互式的 shell,可以在其中执行多个命令。
使用 `invoke_shell` 方法时,需要注意以下几点:
1. `invoke_shell` 方法返回的是一个 `Channel` 对象,可以通过该对象向远程服务器发送命令,并获取命令的输出。
2. `invoke_shell` 方法打开的是一个交互式的 shell,需要手动输入命令并等待命令执行完成后才能获取输出。
3. 由于 `invoke_shell` 方法打开的是一个交互式的 shell,因此需要使用特殊的方式来处理命令的输出,例如使用 `recv` 方法读取输出缓冲区中的数据。
下面是一个使用 `paramiko` 库和 `invoke_shell` 方法连接远程服务器并执行命令的示例代码:
```python
import paramiko
# 创建 SSH 客户端
client = paramiko.SSHClient()
# 允许连接不在 know_hosts 文件中的主机
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接远程服务器
client.connect('hostname', username='username', password='password')
# 打开交互式 shell
channel = client.invoke_shell()
# 发送命令
channel.send('ls\n')
# 等待命令执行完成
while not channel.recv_ready():
pass
# 获取命令输出
output = channel.recv(1024).decode()
# 输出命令输出
print(output)
# 关闭连接
client.close()
```
paramiko invoke_shell
`paramiko` is a Python library used for remote SSH and SFTP connections. The `invoke_shell` method is a part of the `SSHClient` class provided by `paramiko`. It creates an interactive shell session on the remote host and returns a channel object that can be used to send and receive data to and from the shell.
Here's an example usage of `invoke_shell`:
```python
import paramiko
# establish an SSH connection
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('remote_host', username='username', password='password')
# invoke a shell on the remote host
channel = ssh.invoke_shell()
# send a command to the shell
channel.send('ls\n')
# receive the output of the command
output = channel.recv(1024)
# close the shell session and the SSH connection
channel.close()
ssh.close()
```
In this example, `invoke_shell` is used to create a shell session on the remote host. The `send` method is used to send a command (in this case, `ls`) to the shell, and the `recv` method is used to receive the output of the command. Finally, the `close` method is used to close the shell session and the SSH connection.