def test_login_mailaddress_starttls_wrong_credentials_expect_rejected( self): message = EmailMessage() message["From"] = "*****@*****.**" message["To"] = "*****@*****.**" message["Subject"] = "Test" machine: pb.SshMachine = pb.SshMachine(host="remote.example.com", user="******", keyfile="~/.ssh/id_rsa") server = DeployedServer(machine) connection: rpyc.Connection = server.classic_connect() with connection.modules.smtplib.SMTP("mail.example.com", 587) as smtp: smtp.starttls() with self.assertRaises(smtplib.SMTPAuthenticationError) as e: smtp.login(user="******", password="******") self.assertIn("Error: authentication failed", str(e.exception), msg=str(e.exception)) connection.close() server.close() machine.close()
def ssh_transfer_files(ssh_host, ssh_user, ssh_password, source_volume, destination_volume, ssh_port=22): import plumbum import os.path from os import path try: logger.debug("Source image file exists: " + str(path.exists(source_volume))) remote = plumbum.SshMachine(str(ssh_host), user=ssh_user, password=ssh_password) fro = plumbum.local.path(source_volume) to = remote.path(destination_volume) plumbum.path.utils.copy(fro, to) logger.info("File transfered") except Exception as e: logger.exception( "Failure while transfering the file to the server: {}".format( str(e)))
def test_smtp_login_expect_reject(self): message = EmailMessage() message["From"] = "*****@*****.**" message["To"] = "*****@*****.**" message["Subject"] = "Test" machine: pb.SshMachine = pb.SshMachine(host="remote.example.com", user="******", keyfile="~/.ssh/id_rsa") server = DeployedServer(machine) connection: rpyc.Connection = server.classic_connect() with connection.modules.smtplib.SMTP("mail.example.com") as smtp: with self.assertRaises(smtplib.SMTPNotSupportedError) as e: smtp.login(user="******", password="******") smtp.send_message(message, from_addr="*****@*****.**", to_addrs="*****@*****.**") self.assertIn("SMTP AUTH extension not supported by server", str(e.exception), msg=str(e.exception)) connection.close() server.close() machine.close()
def TransferRemote(cameras, targetserver, targetuser, targetpath, targetrawpath, actual=False): photos = GetCameraPhotos(cameras) logpath = os.path.dirname(os.path.abspath(__file__)) logpath = os.path.join(logpath, "logs") MakeDirs(logpath) textname = os.path.join(logpath, "transferlog-"+(datetime.now().strftime("%Y-%m-%d %H.%M.%S"))+".txt") if len(photos) == 0: print("No photos found.") exit(0) with open(textname, "w") as f: print("Connecting to {}".format(targetserver)) f.write("Copying photos to {}:\n\n".format(targetserver)) with plumbum.SshMachine(targetserver, user=targetuser, scp_opts=['-p']) as remote: skip = 0 t = 0 for p in photos: t += 1 destination = (os.path.join(targetpath, p.destination) if not p.raw else os.path.join(targetrawpath, p.destination)) f.write("{} => {}".format(p.location, destination)) src = local.path(p.location) dest = remote.path(destination) if dest.exists(): src_stat = src.stat() dest_stat = dest.stat() if src_stat.st_size == dest_stat.st_size and src_stat.st_mtime == dest_stat.st_mtime and src_stat.st_atime == dest_stat.st_atime: skip += 1 f.write(" EXISTS\n") continue if actual: dest_path = dest.dirname if not dest_path.exists(): dest_path.mkdir() plumbcopy(src, dest) f.write(" OK\n") PrintProgress(str.format("{:d}/{:d} ({:d} skipped) {}", t, len(photos), skip, p.destinationn)) PrintProgress(str.format("{:d}/{:d} ({:d} skipped)", t, len(photos), skip), True) f.write("\nDone.\n") if actual: print("Copied photos.") else: print("Did not actually copy photos.")
def __init__(self, accessconf_dru, ports=None): self.hostname = accessconf_dru.get('hostname', 'localhost') self.user = accessconf_dru.get('user', None) if not self.user and self.hostname == 'localhost': self.user = os.getlogin() if self.hostname != 'localhost': dru = plumbum.SshMachine(self.hostname, user=self.user) else: dru = plumbum.local self.accessible = True dru = self._exec_dru_func() self.dru = dru self.ports = ports
def establish_connection(self, node, user='******'): """ Establishes connection from localhost to node via plumbum.SshMachine. """ try: self.ssh = plumbum.SshMachine( node, user, ssh_opts=('-o StrictHostKeyChecking=no', ), scp_opts=('-o StrictHostKeyChecking=no', )) self.session = self.ssh.session() except Exception as ex: msg = "Unable to establish connection with: %s, reason: %s" raise RemoteException(msg % (node, ex))
def __init__(self, hostname: str, username: str, password: str) -> None: """Initiates SSH connection. Args: hostname: The hostname of the component we want to connect to. username: Username for SSH connection. password: Password for SSH connection. """ # TODO: Check if Paramkio machine can be used with rpyc.DeployedServer. # SshMachine uses an ssh connection for every command, and paramkio use only # one connection. self._machine = plumbum.SshMachine(hostname, user=username, password=password)
def __init__(self, accessconf_dru, ports=None): try: hostname = accessconf_dru['hostname'] except KeyError: hostname = 'localhost' self.hostname = hostname try: user = accessconf_dru['user'] except KeyError: user = None if hostname != 'localhost': dru = plumbum.SshMachine(self.hostname, user=user) else: dru = plumbum.local self.dru = dru self.ports = ports
def test_login_username_smtps_expect_pass(self): message = EmailMessage() message["From"] = "*****@*****.**" message["To"] = "*****@*****.**" message["Subject"] = "Test" machine: pb.SshMachine = pb.SshMachine(host="remote.example.com", user="******", keyfile="~/.ssh/id_rsa") server = DeployedServer(machine) connection: rpyc.Connection = server.classic_connect() with connection.modules.smtplib.SMTP_SSL("mail.example.com", 465) as smtp: smtp.login(user="******", password="******") connection.close() server.close() machine.close()
def start(host=host, port=port): """Start an alpine-linux container running sshd. """ with docker.image('sickp/alpine-sshd', ports={22: (host, port)}, networks=['testlab']): # wait for sshd to come up begin = time.time() while time.time() - begin < 5: try: plumbum.SshMachine(host, port=port, user='******', password='******') except plumbum.machines.session.SSHCommsError: # connection not up yet, cleanup the previous # connection. Otherwise we'll leak file # descriptors like crazy gc.collect() continue break yield host, port
def get_ssh(hostname, port=22, user='******', keyfile=None, password=None, keypw=None, pkey=None): """Get a ``plumbum.SshMachine`` instance. """ settings = {'port': port, 'ssh_opts': SSH_OPTS, 'scp_opts': SSH_OPTS} if user: settings['user'] = user if keyfile: keyfile = os.path.expanduser(keyfile) assert os.path.isfile(keyfile), 'No keyfile {} exists?'.format(keyfile) log.info("Attempting to auth ssh with keyfile {}".format(keyfile)) settings['keyfile'] = keyfile elif password: settings['password'] = password return plumbum.SshMachine(hostname, **settings)
def test_logged_out_starttls_expect_client_host_rejected(self): message = EmailMessage() message["From"] = "*****@*****.**" message["To"] = "*****@*****.**" message["Subject"] = "Test" machine: pb.SshMachine = pb.SshMachine(host="remote.example.com", user="******", keyfile="~/.ssh/id_rsa") server = DeployedServer(machine) connection: rpyc.Connection = server.classic_connect() with connection.modules.smtplib.SMTP("mail.example.com", 587) as smtp: smtp.starttls() with self.assertRaises(smtplib.SMTPRecipientsRefused) as e: smtp.send_message(message, from_addr="*****@*****.**", to_addrs="*****@*****.**") self.assertIn("Client host rejected: Access denied", str(e.exception)) connection.close() server.close() machine.close()
def connect(self, done_callback=None): self.error = "connecting..." self.local = (self.ip == get_routed_ip()) if not self.local: # only connect if it's a separate machine try: # -oBatchMode=yes to disable password auth and just fail if key auth fails self._tunnel = plumbum.SshMachine(self.ip, user=self.user, ssh_opts=['-oBatchMode=yes']) except (plumbum.machines.session.SSHCommsChannel2Error, plumbum.machines.session.SSHCommsError): self.error = "SSH connection failure" self._tunnel = None return self._rpc = rpyc.ssh_connect(self._tunnel, self.port) else: self._rpc = rpyc.connect("localhost", self.port) self.error = None if done_callback is not None: done_callback(self.name)