Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def manual_auth(t, username, hostname, keyfile_path):
"""Authentication using manual input"""
if keyfile_path:
try:
if not os.path.exists(keyfile_path):
print("{} doesn't exist".format(keyfile_path))
sys.exit(2)
key = paramiko.RSAKey.from_private_key_file(keyfile_path)
except paramiko.PasswordRequiredException:
password = getpass.getpass('RSA key password: ')
key = paramiko.RSAKey.from_private_key_file(keyfile_path, password)
t.auth_publickey(username, key)
else:
pw = getpass.getpass('Password for %s@%s: ' % (username, hostname))
t.auth_password(username, pw)
'toPort': 5432,
'protocol': "tcp"
},
instanceName=INSTANCE_NAME
)
logger.info("\t\t{0}".format(response_dict))
logger.info('\t\tWaiting 30 seconds... instance is booting')
time.sleep(30)
instance_ip = instance_dict["publicIpAddress"]
cpu_count = instance_dict["hardware"]["cpuCount"]
logger.info("\t\tPublic IP address: {0}".format(instance_ip))
# create SSH client
key = paramiko.RSAKey.from_private_key_file(PEM_FILE)
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=instance_ip, username="ubuntu", pkey=key)
logger.info("Connected to new server via SSH : {0}".format(datetime.now() - full_start_time))
logger.info("")
# run each bash command
bash_file = os.path.abspath(__file__).replace(".py", ".sh")
bash_commands = open(bash_file, 'r').read().split("\n")
for cmd in bash_commands:
if cmd[:1] != "#" and cmd[:1].strip(" ") != "": # ignore comments and blank lines
# replace text with passwords if required
if "" in cmd:
def main(userhost, password, port=22):
'''
Setup ssh keys, return ReturnBox
'''
logger.info(f'Setting up ssh keys for {userhost}...')
rb = util.ReturnBox()
# app key
user, host = userhost.split('@')
seckey = util.get_app_key(user)
# Check if keys need to be generated
pubkey = ''
if has_app_keys(user):
logger.info('Private key already exists.')
sk = paramiko.RSAKey.from_private_key_file(seckey)
pubkey = f'ssh-rsa {sk.get_base64()} {userhost}'
else:
rbkey = generate_keys(seckey, userhost)
if rbkey.error:
rbkey.returncode = util.ReturnCode.BAD_SSH
return rbkey
else:
pubkey = rbkey.output
# connect
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
rb.error = ''
try:
logger.info('Connecting using password...')
def __init__(self, local_path, remote_url, key=None, port=22):
self.local_path = local_path
self.username, self.hostname = remote_url.split('@', 1)
self.hostname, self.remote_path = self.hostname.split(':', 1)
self.password = None
if ':' in self.username:
self.username, self.password = self.username.split(':', 1)
self.port = port
self.chown = False
self.pkey = None
if key:
self.pkey = paramiko.RSAKey.from_private_key_file(key)
if self.username == 'root':
self.chown = True
self.transport = paramiko.Transport((self.hostname, self.port))
self.transport.connect(
username=self.username,
password=self.password,
pkey=self.pkey)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
def __init__(self,username=username,ip=None,ssh_port=ssh_port,keyfile=keyfile,password=password,key_type=key_type):
self.username = username
self.ip = str(ip)
self.ssh_port= int(ssh_port)
self.keyfile = keyfile
self.password = password
self._ssh = paramiko.SSHClient()
self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if self.keyfile:
if key_type == 'rsa':
self.key = paramiko.RSAKey.from_private_key_file(self.keyfile)
if key_type == 'dsa' or key_type == 'dss':
self.key = paramiko.DSSKey.from_private_key_file(self.keyfile)
self._ssh.connect(self.ip, self.ssh_port, self.username, pkey=self.key, timeout=15)
else:
if self.username == 'root':
self._ssh.connect(hostname=self.ip,port=self.ssh_port,username=self.username,password=self.password,timeout=15)
def Run(self,cmd):
def connect_with_encrypted_keyfile(self, private_key_path, password):
key = paramiko.RSAKey.from_private_key_file(private_key_path, password=password)
self.ssh.connect(hostname = self.server,
port = self.port,
username = self.username,
pkey = key)
# Get hostname and port to use
hostname = self.channeldict['host']
try:
port = int(self.channeldict['port'])
except:
port = 22 # default port for sftp
if self.userscript and hasattr(self.userscript,'hostkey'):
hostkey = botslib.runscript(self.userscript,self.scriptname,'hostkey',channeldict=self.channeldict)
else:
hostkey = None
if self.userscript and hasattr(self.userscript,'privatekey'):
privatekeyfile,pkeytype,pkeypassword = botslib.runscript(self.userscript,self.scriptname,'privatekey',channeldict=self.channeldict)
if pkeytype == 'RSA':
pkey = paramiko.RSAKey.from_private_key_file(filename=privatekeyfile,password=pkeypassword)
else:
pkey = paramiko.DSSKey.from_private_key_file(filename=privatekeyfile,password=pkeypassword)
else:
pkey = None
if self.channeldict['secret']: #if password is empty string: use None. Else error can occur.
secret = self.channeldict['secret']
else:
secret = None
# now, connect and use paramiko Transport to negotiate SSH2 across the connection
self.transport = paramiko.Transport((hostname,port))
self.transport.connect(username=self.channeldict['username'],password=secret,hostkey=hostkey,pkey=pkey)
self.session = paramiko.SFTPClient.from_transport(self.transport)
channel = self.session.get_channel()
channel.settimeout(botsglobal.ini.getint('settings','ftptimeout',10))
self.set_cwd()
def connect(self):
if self.__connected():
self.disconnect()
log('[ssh] Connecting to %s ...' % self.public_ip)
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(self.public_ip, username=self.username, pkey=paramiko.RSAKey.from_private_key_file(EC2_PKEY_FILE))
# Connect but fails if the keys change. load_host_keys can
# handle hashed known_host entries.
if self.strict_ssh_host_key_policy:
ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
else:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if self.password:
ssh.connect(self.ip,
port=self.port,
username=self.login,
password=self.password,
timeout=self.conn_timeout)
elif self.privatekey:
pkfile = os.path.expanduser(self.privatekey)
privatekey = paramiko.RSAKey.from_private_key_file(pkfile)
ssh.connect(self.ip,
port=self.port,
username=self.login,
pkey=privatekey,
timeout=self.conn_timeout)
else:
msg = _("Specify a password or private_key")
raise exception.CinderException(msg)
if self.conn_timeout:
transport = ssh.get_transport()
transport.set_keepalive(self.conn_timeout)
return ssh
except Exception as e:
msg = _("Error connecting via ssh: %s") % six.text_type(e)
LOG.error(msg)
def runScript(self,deployCommand):
self.s = paramiko.SSHClient()
self.s.load_system_host_keys()
self.s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.key = paramiko.RSAKey.from_private_key_file(RSA_PRIVATE_KEY_FILE)
self.s.connect(hostname=self.masterIp,
port=int(22),
username="root",
pkey=self.key,
timeout=self.deployTimeout)
stdin, stdout, stderr = self.s.exec_command(deployCommand,get_pty=True)
number=0
try:
while True:
nextline = stdout.readline().strip()
if not nextline:
time.sleep(1)
number +=1
if number > 5: