Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __init__(self, hostname, port, username, private_ssh_key_filename):
self.hostname = hostname
self.port = port
self.username = username
#print "Created TestingNode with hostname %s, port %i, username %s" % (hostname, port, username)
# read private key from file to get access to the node
if True: # Always use RSA for now
self.private_ssh_key = paramiko.RSAKey(filename=private_ssh_key_filename)
else:
self.private_ssh_key = paramiko.DSSKey(filename=private_ssh_key_filename)
self.global_lock_file = "/tmp/cloudtest_lock"
system_random = random.SystemRandom()
self.global_build_path = "/tmp/cloudtest_build_" + str(system_random.randint(10000000, 99999999));
self.global_bench_path = "/tmp/cloudtest_bench_" + str(system_random.randint(10000000, 99999999));
self.global_test_path = "/tmp/cloudtest_test_" + str(system_random.randint(10000000, 99999999));
#print "Installing build into %s\n" % self.global_build_path
self.basedata_installed = False
self.ssh_transport = None
We support RSA, ECDSA and Ed25519 keys and return instances of:
* paramiko.rsakey.RSAKey
* paramiko.ecdsakey.ECDSAKey
* paramiko.ed25519key.Ed25519Key (requires paramiko >= 2.2)
"""
# I don't think there is a key type independent way of doing this
public_key_blob = b64decode(self.key_base64)
if self.key_algorithm.startswith('ssh-ed25519'):
try:
return Ed25519Key(data=public_key_blob)
except NameError:
raise ValidationError('Paramiko too old to load ed25519 keys')
elif self.key_algorithm.startswith('ecdsa-'):
return ECDSAKey(data=public_key_blob)
elif self.key_algorithm.startswith('ssh-rsa'):
return RSAKey(data=public_key_blob)
raise SSHException('Key is not RSA, ECDSA or Ed25519')
server = [rhost, int(port)] # our ssh server
remote = [rhost, int(rport)] # what we want to tunnel
client = paramiko.SSHClient() # use the paramiko SSHClient
client.load_system_host_keys() # load SSH keys
client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # automatically add SSH key
# loop until you connect successfully
while True:
try:
pkey = None
if privatekey:
fkey = StringIO(privatekey)
if 'BEGIN RSA' in privatekey:
pkey = paramiko.RSAKey.from_private_key(fkey)
elif 'BEGIN DSA' in privatekey or 'BEGIN DSS' in privatekey:
pkey = paramiko.DSSKey.from_private_key(fkey)
elif 'BEGIN ECDSA' in privatekey:
pkey = paramiko.ECDSAKey.from_private_key(fkey)
print('[*] Tunneling SSH, this takes a moment.')
client.connect(server[0], server[1], username=user, pkey=pkey, look_for_keys=False, password=password)
except Exception as e:
print('[X] Failed to connect to %s:%d: %r Trying to connect again...' % (server[0], server[1], e))
time.sleep(5)
else:
# let you know if you connected successfully then finish
print('[*] Connected to %s:%d: successfully' % (server[0], server[1]))
break
def connect(self, host, userid, password, ssh_key_string=None):
_method_ = "UbuntuPlugin.connect"
try:
self.userid = userid
self.password = password
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if ssh_key_string:
private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password)
self.client.connect(host, username=userid, pkey=private_key, timeout=30,
allow_agent=False)
else:
self.client.connect(host, username=userid, password=password, timeout=30,
allow_agent=False)
if not self._is_ubuntu():
raise exceptions.InvalidDeviceException(
"Device is not a Ubuntu Device")
except paramiko.AuthenticationException:
logging.error("%s::userid/password combination not valid. host=%s userid=%s",
_method_, host, userid)
raise exceptions.AuthenticationException(
"userid/password combination not valid")
except (paramiko.ssh_exception.SSHException, OSError, socket.timeout) as e:
logging.exception(e)
logging.error("%s::Connection timed out. host=%s", _method_, host)
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import paramiko, testrun, threading, traceback, sys
from unixshell import interactive_shell, process_commandline
from utils import TextChannel, log_append, noexceptwrap
paramiko.util.log_to_file('logs/tcp_ssh_server_paramiko.log')
host_key_rsa = paramiko.RSAKey(filename='secrets/tcp_ssh_rsa')
host_key_dss = paramiko.DSSKey(filename='secrets/tcp_ssh_dss')
class Server(paramiko.ServerInterface):
def __init__(self, socket_peername):
self.socket_peername = socket_peername
self.username = None
def check_channel_request(self, kind, chanid):
print("Channel requested: kind={}".format(kind))
if kind == 'session':
return paramiko.OPEN_SUCCEEDED
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
def check_auth_password(self, username, password):
print("Password-based authentication: user={} pass={}".format(username, password))
log_append('tcp_ssh_passwords', username, password, *self.socket_peername)
try:
current_app.logger.debug(
"Connecting to {0}@{1}:{2}".format(user, host, port)
)
ssh = paramiko.SSHClient()
# allow connection to the new unknown host
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# open the ssh connection
if password:
current_app.logger.debug("Using password")
ssh.connect(host, username=user, port=port, password=password)
elif ssh_priv_key:
current_app.logger.debug("Using RSA private key")
pkey = paramiko.RSAKey.from_private_key_file(
ssh_priv_key, ssh_priv_key_pass
)
ssh.connect(host, username=user, port=port, pkey=pkey)
else:
current_app.logger.error(
"No password or private key provided. Can't proceed"
)
raise paramiko.ssh_exception.AuthenticationException
# open the sftp session inside the ssh connection
sftp = ssh.open_sftp()
# make sure that the destination path exist
try:
current_app.logger.debug("Creating {0}".format(dst_path))
sftp.mkdir(dst_path)
Because seting socket timeout to be None will cause client.close()
blocking, here we have to rewrite method create() and use default
socket timeout value 0.1.
"""
try:
ssh = paramiko.SSHClient()
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") % e
LOG.error(msg)
def get_host_key(cls):
logger.debug("Get ssh server host key")
if not os.path.isfile(cls.host_key_path):
cls.host_key_gen()
return paramiko.RSAKey(filename=cls.host_key_path)
def scp2(Key, arg, wline, swline):
try:
ssh = paramiko.SSHClient()
key = paramiko.RSAKey.from_private_key_file(key_file)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for ip in ips:
ip = ip.strip()
Redis.lpush(Key, 'sync ' + line + ' to ' + ip + '\n')
ssh.connect(ip, 22, username, pkey=key, timeout=30)
scp = SCPClient(ssh.get_transport())
cmd = 'mkdir -p ' + wline
stdin, stdout, stderr = ssh.exec_command(cmd)
if os.path.isdir(swline):
scp.put(swline, wline, recursive=True)
else:
scp.put(swline, swline)
ssh.close()
if arg == 'publish':
if os.path.isdir(swline):
dirs = create_paths(swline)
def private_key_from_string(private_key):
for cls in (paramiko.RSAKey, paramiko.ECDSAKey, paramiko.DSSKey):
try:
f = six.StringIO(private_key)
key = cls.from_private_key(f)
except paramiko.SSHException:
continue
return key
raise paramiko.SSHException("not a valid private key file")