Created
June 4, 2022 04:32
-
-
Save x0nu11byt3/ef0f417e34d6c5dee75e2a5897784c35 to your computer and use it in GitHub Desktop.
SSH Client with a simple connection and run an simple command. For to connect with a normal user without many privileges since to use the root user more processes. Iptables to open a port is enabled as follows: iptables -A INPUT -p tcp -m tcp --dport <port> -j ACCEPT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import sys | |
import paramiko | |
class SSHClient: | |
def __init__(self,hostname, port, username, password): | |
self._port = port | |
self._hostname = hostname | |
self._username = username | |
self._password = password | |
def log(self,filename): | |
""" | |
with this line you create a log file to see more details of your connection and your ssh client | |
""" | |
paramiko.util.log_to_file( filename + '.log' ) | |
def init_client(self): | |
# create your ssh client object and initialize it | |
ssh_client = paramiko.SSHClient() | |
# add a policy to accept user authentication services | |
ssh_client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) | |
try: | |
# starts the connection if no exception is successfully made | |
ssh_client.connect(self._hostname , port=self._port, username=self._username, password=self._password) | |
print('Connected successfully') | |
# executes the command at the moment only executes simple commands, like: ls, less, who, cat, cd | |
stdin, stdout, stderr = ssh_client.exec_command("ls -la /home") | |
# see the output status of the channel that implicitly opens the paramiko | |
stdout.channel.recv_exit_status() | |
# if applicable read the output lines as commands that give an example of output ls, less, who, cat, cd | |
lines = stdout.readlines() | |
for line in lines: | |
print(line) | |
ssh_client.close() | |
except paramiko.ssh_exception.AuthenticationException as message: | |
print(message) | |
except paramiko.ssh_exception.SSHException as message: | |
print(message) | |
except paramiko.AuthenticationException as message: | |
print(message) | |
def main(argv): | |
ssh_client = SSHClient("127.0.0.1",22,"youruser","yourpassword") | |
ssh_client.log('ssh_client') | |
ssh_client.init_client() | |
if __name__ == '__main__': | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment