要使用Python连接Linux服务器,你可以使用`paramiko`库。以下是使用`paramiko`库连接Linux服务器的基本步骤:
1. 安装`paramiko`库:
```bash
pip install paramiko
2. 导入`paramiko`库并创建一个`SSHClient`对象:
```python
import paramiko
ssh = paramiko.SSHClient()
3. 设置`SSHClient`对象以允许连接不在`known_hosts`文件中的主机,并设置连接超时时间(可选):
```python
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='your_linux_ip', port=22, username='your_username', password='your_password', timeout=10)
4. 使用`exec_command`方法执行Linux命令:
```python
stdin, stdout, stderr = ssh.exec_command('your_command_here')
5. 读取命令执行结果:
```python
result = stdout.read().decode()
print(result)
6. 关闭SSH连接:
```python
ssh.close()
这是一个完整的示例代码:
```python
import paramiko
def ssh_connect_and_execute_command(ip, username, password, command):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, 22, username=username, password=password, timeout=10)
stdin, stdout, stderr = ssh.exec_command(command)
result = stdout.read().decode()
print(result)
except Exception as e:
print(f"Error: {e}")
finally:
ssh.close()
if __name__ == "__main__":
ssh_connect_and_execute_command('192.168.8.120', 'root', 'love-520', 'cat /etc/passwd')
请确保替换示例代码中的`your_linux_ip`、`your_username`、`your_password`和`your_command_here`为实际的Linux服务器IP地址、用户名、密码和要执行的命令。
如果你需要上传或下载文件,可以使用`SFTP`或`SFTPClient`对象:
```python
sftp = ssh.open_sftp()
sftp.get('remote_file_path', 'local_file_path') 从Linux下载文件到本地
sftp.put('local_file_path', 'remote_file_path') 从本地上传文件到Linux