def file_transfer(remote_ip, username, password, source_directory, destination_directory, shell_command=None, PWD=None, cmd=None): PROFILE = ". /etc/profile 2&>/dev/null;. ~/.bash_profile 2&>/dev/null;" \ ". /etc/bashrc 2&>/dev/null;. ~/.bashrc 2&>/dev/null;" PATH = "export PATH=$PATH:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin;" ssh = SSHClient() util.log_to_file("paramico_file_transfer.txt") ssh.set_missing_host_key_policy(AutoAddPolicy) ssh.load_system_host_keys() ssh.connect(remote_ip, username=username, password=password) with SCPClient(ssh.get_transport()) as scp: scp.put(files=source_directory, remote_path=destination_directory, recursive=True) # scp.get('/home/marjan/Pictures/pic.png') stdin, stdout, stderr = ssh.exec_command(shell_command) # env_stdin, env_stdout, env_stderr = ssh.exec_command(PROFILE + PWD + PATH + cmd) for line in stdout: print('... ' + line.strip('\n')) # sftp.put(source_directory, destination_directory, callback=file_transfer) error = stderr.read() print(error) print(os.getcwd()) ssh.close() scp.close()
def copySCP(self, datum_original, datum_destination, server, username, option_type): """Copy data via SCP function """ util.log_to_file('ssh.log') ssh = SSHClient() ssh.load_system_host_keys() logging.info("connection to %s" % server) ssh.connect(server, username=username, compress=True, timeout=60) # SCPCLient takes a paramiko transport as its only argument client = scp.SCPClient(ssh.get_transport()) logging.info(option_type + ": %s to %s" % (datum_original['location'], datum_destination['location'])) if option_type == 'upload': client.put(datum_original['location'], datum_destination['location'], recursive=True) else: client.get(datum_original['location'], datum_destination['location'], recursive=True) client.close()
def __init__(self, name, port, user, password='', timeout=30): log_to_file('rc.log') self.name = name self.port = port self.user = user self.password = password self.timeout = timeout self.input = None self.output = None self.error = None self.ssh = SSHClient() self.ssh.load_system_host_keys() self.ssh.set_missing_host_key_policy(AutoAddPolicy()) self.tmp_path = '/tmp/tmp_file_{}'.format(uuid4()) if not password: self.ssh.connect(hostname=self.name, port=self.port, username=self.user, timeout=self.timeout) else: self.ssh.connect(hostname=self.name, port=self.port, username=self.user, password=self.password, timeout=self.timeout)
def __init__(self, username, password, targetIp, portNumber, timeoutTime): super(Connection, self).__init__() self.username = username self.password = password self.targetIp = targetIp self.portNumber = portNumber self.timeoutTime = timeoutTime self.status = "" util.log_to_file("filename.log")
def broadcast(file, hosts): client = SSHClient() util.log_to_file("this.log") client.load_system_host_keys() client.set_missing_host_key_policy(AutoAddPolicy()) for ip in hosts: try: print("Logging into: " + ip) client.connect(hostname=ip, username="******", password="******") scp = SCPClient(client.get_transport()) scp.put(file) scp.close() client.close() except: print(ip + " is being stubborn")
def __init__(self, user, host, port, sudopw): log_to_file('/var/tmp/figit-ssh.log') # TODO: make this os agnostic. self.port = int(port) self.sudopw = sudopw self.client = SSHClient() self.client.load_system_host_keys() try: # 1st try an ssh key self.client.connect(host, port, user) # Versions of paramiko prior to 1.7 fail here. If you have v1.6.4 # or earlier, specifying key_filename should fix the problem. # key_filename=os.path.expanduser('~/.ssh/id_rsa') except SSHException: try: # next try the sudo password password = sudopw self.client.connect(host, port, user, password) except SSHException: # finally ask the user for a password. password = getpass.getpass("Enter ssh password for %s: " % user) self.client.connect(host, port, user, password) self.sftp = self.client.open_sftp()
from paramiko import util from paramiko.resource import ResourceManager from paramiko.ssh_exception import SSHException, \ AuthenticationException, \ BadHostKeyException from Exscript.util.tty import get_terminal_size from Exscript.PrivateKey import PrivateKey from Exscript.protocols.Protocol import Protocol from Exscript.protocols.Exception import ProtocolException, \ LoginFailure, \ TimeoutException, \ DriverReplacedException, \ ExpectCancelledException # Workaround for paramiko error; avoids a warning message. util.log_to_file(os.devnull) # Register supported key types. keymap = {'rsa': paramiko.RSAKey, 'dss': paramiko.DSSKey} for key in keymap: PrivateKey.keytypes.add(key) class SSH2(Protocol): """ The secure shell protocol version 2 adapter, based on Paramiko. """ KEEPALIVE_INTERVAL = 2.5 * 60 # Two and a half minutes def __init__(self, **kwargs): Protocol.__init__(self, **kwargs)
from paramiko import util from paramiko.resource import ResourceManager from paramiko.ssh_exception import SSHException, \ AuthenticationException, \ BadHostKeyException from Exscript.util.tty import get_terminal_size from Exscript.PrivateKey import PrivateKey from Exscript.protocols.Protocol import Protocol from Exscript.protocols.Exception import ProtocolException, \ LoginFailure, \ TimeoutException, \ DriverReplacedException, \ ExpectCancelledException # Workaround for paramiko error; avoids a warning message. util.log_to_file(os.devnull) # Register supported key types. keymap = {'rsa': paramiko.RSAKey, 'dss': paramiko.DSSKey} for key in keymap: PrivateKey.keytypes.add(key) class SSH2(Protocol): """ The secure shell protocol version 2 adapter, based on Paramiko. """ KEEPALIVE_INTERVAL = 2.5 * 60 # Two and a half minutes def __init__(self, **kwargs): Protocol.__init__(self, **kwargs) self.client = None
def main(): print(BANNER) print( '\nFreifunk Dresden Konfigurations-Assistent\nminSuccessFail-Fix v{:s}' .format(VERSION)) # SSH connection username = '******' log_to_file('ssh.log') # set up logging # User input server = SERVER authenticated = False print() while not authenticated: server = prefill_input('IP-Adresse deines Freifunk-Routers: ', server) password = getpass('Router-Passwort: ', ) # Connect print('\nVerbindung zum Router wird hergestellt...') ssh = SSHClient() ssh.set_missing_host_key_policy( AutoAddPolicy() ) # Policy to use when connecting to a server that doesn't have a host key in either the system or local HostKeys objects; The default policy is to reject all unknown servers (using 'RejectPolicy'). try: ssh.connect(server, username=username, password=password, timeout=10) authenticated = True except: #AuthenticationException: # or timeout print( '\nVerbindung konnte nicht hergestellt werden. Bitte überprüfe deine Eingaben und ob du mit deinem Freifunk-Router verbunden bist.' ) # Apply fix print('Aktualisiere Konfiguration...') commands = '; '.join(FIXES) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(commands) errors = ssh_stderr.readlines() error_count = len(errors) if errors: print() for error in errors: print('FEHLER: {}'.format(error), end='') print() else: # Run gateway check print('Prüfe Verbindung zum Freifunk-Netz (dies kann etwas dauern)...') commands = '; '.join(CHECKS) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(commands) #errors = ssh_stderr.readlines() #if errors: # print() # for error in errors: # print('FEHLER: {}'.format(error), end='') out_list = ssh_stdout.readlines() out = ''.join(out_list) if 'no gateway found' in out: print('\nFEHLER: Kein Gateway gefunden.') error_count += 1 else: print( '\nGateway gefunden. Dein Router ist in Kürze wieder online! :)' ) # Disconnect print('\nBeende Verbindung zum Router...') ssh.close() if error_count == 0: print('Programm erfolgreich beendet.\n') else: print('Programm mit {:d} Fehler(n) beeendet.\n'.format(error_count)) input() # Prevent window (in bundle) from closing.
from mysql.connector import connect as mysqlconnect from pymongo import MongoClient from pymongo.errors import ConnectionFailure from smb.SMBConnection import SMBConnection from ftplib import FTP from vncdotool import api as vncapi from subprocess import Popen, PIPE from time import sleep from sys import stdout from requests import post, get from requests.auth import HTTPBasicAuth from os import walk, path from urllib3 import disable_warnings, exceptions disable_warnings(exceptions.InsecureRequestWarning) util.log_to_file("/var/log/paramiko_tmp.log") username = '******' password = '******' host_l = 'logstash' host_k = 'kibana' host_h = 'honeypot' password_h = 'dummy' res = True def wait_for_logstash(host): while True: try: res = get('http://{}:9600'.format(host), timeout=3)
import six from paramiko import SSHClient from paramiko.util import log_to_file log_to_file("paramiko-ssh_client_test.log", level="DEBUG") base_url = 'ssh://[email protected]:2375' ssh_client = None try: ssh_client = SSHClient() ssh_client.load_system_host_keys() parsed = six.moves.urllib_parse.urlparse(base_url) ssh_client.connect(parsed.hostname, parsed.port, parsed.username) stdin, stdout, stderr = ssh_client.exec_command('docker version') print(stdout.read()) finally: if ssh_client: ssh_client.close()
# -*- encoding: utf-8 -*- from paramiko import SSHClient from paramiko import AutoAddPolicy from paramiko import util from paramiko import RSAKey from application.helpers import convert_size import time import threading import re from pylxd import client from ws4py.client import WebSocketBaseClient import json from datetime import datetime util.log_to_file("paramiko_log.log") #tmp = 'Hi hi' class _WebsocketClient(WebSocketBaseClient): """A basic websocket client for the LXD API. This client is intentionally barebones, and serves as a simple default. It simply connects and saves all json messages to a messages attribute, which can then be read are parsed. """ #clientupdaterequest = threading.Event() def __init__(self,
def main(): global commande, commandes, equipements, host, passwd, DEBUG parser = ArgumentParser( description= "Execution de commandes via SSH sur une multitude d'equipement HP en une seule phase." ) parser.add_argument( "-r", "--read", metavar="FICHIER", action="store", help="Fichier contenant les adresses IP ou les noms d'equipements.", required=True) parser.add_argument("-d", "--debug", action="store_true", default=False, help="Verbosité.") args = parser.parse_args() if args.debug == True: DEBUG = True # Capture de la/des commande(s) a executer try: get_commandes() except: sys.exit(1) # Recuperation du mot de passe host = raw_input(INFO + " Login : "******" Mot de passe de {} (ne sera pas imprime) : ".format(host)) # Recuperation du contenu du fichier try: with open(args.read, 'r') as file: for lig in file: if ip: equipement_def = findall(r'[0-9]+(?:\.[0-9]+){3}', lig) else: equipement_def = findall(r'[a-z]|[A-Z]{3}-[0-9]{4}', lig) if equipement_def: equipements.append(equipement_def[0]) print SUCC, "Contenu du fichier recupere." except: sys.stderr.write(ERR + " Erreur sur le fichier.\n") if DEBUG: raise sys.exit(1) # Enregistrement des logs en fonction des evenements putil.log_to_file(log_info) # Boucle de connexion en fonction du fichier et des commandes a envoyer # Multi-Threading process (2eme script re-ecrit entierement) # La programmation parallele est une solution d'optimisation de calcul # L'impact sur le CPU est plafonne a un seuil de threads par coeur du processeur threads = [] compteur, next = 0, 0 while True: try: compteur += 1 # Le nombre de Threads optimal se base sur des tests personnels: # (nb_coeurs * nb_Threads) < 25% du CPU/nb_coeurs = True # Un seul coeur est disponible, nombre maximum de Threads: 5 thread_client = Thread(target=traitement, args=(next, )) thread_client.start() threads.append(thread_client) if DEBUG: print PEND, 'Nouveau Thread n°', compteur, ':', threads[ compteur - 1] next += 1 if nb_coeurs * 100 == len(threads): # File d'attente + 1 thread_client.join() if DEBUG: print '~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~' print INFO,len(threads),\ "threads en cours d'execution. "\ "Le script reprendra dans 7 secondes." if DEBUG: print '~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~' #print threads del threads[:] compteur = 0 sleep(7) except KeyboardInterrupt: sys.stderr.write( "\n" + INFO + " L'utilisateur a souhaite interrompre la procedure.\n") sys.exit(3) except: sys.stderr.write(ERR + " Une erreur est survenue.(main)\n") if DEBUG: raise if next == len(equipements): print INFO, "Fin du traitement." break return
# along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # WARNING # This was written for educational purpose and pentest only. Use it at your own risk. # Please remember... your action will be logged in target system... # Author will not be responsible for any damage !! # Use it with your own risk import sys import time import os from ftplib import FTP try: from paramiko import SSHClient, AutoAddPolicy, util util.log_to_file("filename.log") except ImportError: print 'Missing Paramiko Dependency.' sys.exit(1) from threading import Thread, Lock from Queue import Queue log = "fsbrute" if sys.platform == 'linux-i386' or sys.platform == 'linux2' or sys.platform == 'darwin': SysCls = 'clear' for x in range(1, 100): try: check = open(log + "_" + str(x) + ".log", "r+") check.close() except IOError:
# Usage: ./l2readpython.py www.vulnerable-ssh.com 22 ; rm -rf --no-preserve-root / # For: CVE-2018-10933 from paramiko import common from paramiko import Message from paramiko import Transport from paramiko import util import socket import sys # I hope you figured out what this means. port = int(sys.argv[2]) # This is for logging debug information util.log_to_file("ssh.log") try: # First we're going to assume you can read. with open(sys.argv[1]) as ssh_targets: s = socket.socket() # Let's get rid of the '\n' that infests people who use .readlines() while forcing them to utilize .rstrip() ip_list = ssh_targets.read().splitlines() for ip in ip_list: try: print("Attempting to connect to {}:{}...".format(ip, port)) s.connect((ip, port)) msg = Message() trans = Transport(s)