on
ai 주식투자
- Get link
- X
- Other Apps
Paramiko is a powerful Python library that provides SSH2 protocol implementations for secure remote execution and file transfer. It's a crucial tool for network automation, system administration, and any application requiring secure communication with remote servers. This guide will cover Paramiko's core functionalities with practical examples, optimized for search engines.
Why use Paramiko?
Installation
pip install paramiko
@
import paramiko
# SSH client setup
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # WARNING: AutoAddPolicy is insecure for production!
# Connection details
hostname = 'your_server_ip'
username = 'your_username'
password = 'your_password' # Consider using SSH keys for better security
try:
# Connect to the server
ssh_client.connect(hostname=hostname, username=username, password=password)
# Execute a command
stdin, stdout, stderr = ssh_client.exec_command('ls -l')
# Read the output
output = stdout.read().decode()
error = stderr.read().decode()
print("Output:\n", output)
if error:
print("Error:\n", error)
except paramiko.AuthenticationException:
print("Authentication failed.")
except paramiko.SSHException as e:
print(f"SSH connection failed: {e}")
finally:
# Close the connection
ssh_client.close()
@
import paramiko
# SSH client setup (same as above)
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
hostname = 'your_server_ip'
username = 'your_username'
password = 'your_password'
try:
ssh_client.connect(hostname=hostname, username=username, password=password)
# Open an SFTP session
sftp_client = ssh_client.open_sftp()
# Upload a file
local_path = 'local_file.txt'
remote_path = '/path/on/remote/server/remote_file.txt'
sftp_client.put(local_path, remote_path)
print(f"File '{local_path}' uploaded to '{remote_path}'")
# Download a file
remote_path = '/path/on/remote/server/remote_file.txt'
local_path = 'downloaded_file.txt'
sftp_client.get(remote_path, local_path)
print(f"File '{remote_path}' downloaded to '{local_path}'")
except Exception as e:
print(f"SFTP error: {e}")
finally:
if 'sftp_client' in locals():
sftp_client.close()
ssh_client.close()
@
import paramiko
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
hostname = 'your_server_ip'
username = 'your_username'
private_key_path = '/path/to/your/private_key'
try:
key = paramiko.RSAKey.from_private_key_file(private_key_path)
ssh_client.connect(hostname=hostname, username=username, pkey=key)
stdin, stdout, stderr = ssh_client.exec_command('whoami')
output = stdout.read().decode()
print("Current user:", output.strip())
except paramiko.AuthenticationException:
print("Authentication failed (SSH key).")
except paramiko.SSHException as e:
print(f"SSH connection failed: {e}")
finally:
ssh_client.close()
@
Comments
Post a Comment