帮我写一个使用 ssh 库远程执行sh /text/text.sh
时间: 2023-12-04 21:01:39 浏览: 28
好的,以下是一个使用 `ssh` 库远程执行 shell 脚本的示例代码:
```python
import ssh
# 建立 SSH 连接
client = ssh.SSHClient()
client.load_system_host_keys()
client.connect('remote_host', username='username', password='password')
# 执行 shell 命令
command = 'sh /text/text.sh'
stdin, stdout, stderr = client.exec_command(command)
# 输出执行结果
print(stdout.read().decode())
# 关闭 SSH 连接
client.close()
```
在这个示例中,我们首先使用 `SSHClient()` 方法创建一个 SSH 连接,然后使用 `connect()` 方法连接到远程主机。接下来,我们使用 `exec_command()` 方法执行 shell 命令,并使用 `read()` 方法读取命令的输出结果。最后,我们使用 `close()` 方法关闭 SSH 连接。
请注意,您需要将示例代码中的 `remote_host`、`username` 和 `password` 替换为实际的远程主机地址、用户名和密码。
相关问题
帮我写一个django 使用ssh库远程执行sh /text/text.sh
好的,以下是使用paramiko库在Django中远程执行sh /text/text.sh的示例代码:
```python
import paramiko
def execute_remote_script():
# SSH连接的配置信息
hostname = 'remote_host'
username = 'remote_user'
password = 'remote_password'
port = 22
# 创建SSH客户端并连接远程主机
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, port=port, username=username, password=password)
# 执行远程脚本
stdin, stdout, stderr = ssh.exec_command('/bin/bash /text/text.sh')
# 获取执行结果
output = stdout.read().decode('utf-8')
error = stderr.read().decode('utf-8')
# 关闭SSH连接
ssh.close()
return output, error
```
你需要将hostname、username和password替换为你的远程主机的实际值,然后在你的Django视图函数中调用execute_remote_script()函数即可。注意,由于SSH连接是一个耗时的操作,建议将execute_remote_script()函数放在异步任务中执行,以避免阻塞Django应用程序。
如何使用PySSH库来远程控制执行sh /text/text.sh
可以使用PySSH库的run方法来执行远程命令,可以将`sh /text/text.sh`作为参数传递给run方法来执行。示例代码如下:
```python
from pyssh import SSHClient
ssh = SSHClient('192.168.1.100', 'username', 'password')
result = ssh.run('sh /text/text.sh')
print(result.stdout)
```
上述代码创建了一个SSH连接对象,连接到IP地址为192.168.1.100的远程主机,并使用指定的用户名和密码进行连接。然后执行了远程命令`sh /text/text.sh`,并将结果存储在名为result的变量中。最后打印了结果的标准输出。
需要注意的是,执行远程命令时需要确保远程主机上存在相应的文件和权限。如果需要sudo权限来执行该命令,可以在连接SSH时指定相应的sudo密码。