示例#1
0
def ssh_connect(ip, username, connect_kwargs={}, timeout=60):
    if 'fake' in ip:
        return fakeprovider.FakeSSHClient()
    # HPcloud may return ECONNREFUSED or EHOSTUNREACH
    # for about 30 seconds after adding the IP
    for count in iterate_timeout(timeout, exceptions.SSHTimeoutException,
                                 "ssh access"):
        try:
            client = SSHClient(ip, username, **connect_kwargs)
            break
        except paramiko.SSHException as e:
            # NOTE(pabelanger): Currently paramiko only returns a string with
            # error code. If we want finer granularity we'll need to regex the
            # string.
            log.exception('Failed to negotiate SSH: %s' % (e))
        except paramiko.AuthenticationException as e:
            # This covers the case where the cloud user is created
            # after sshd is up (Fedora for example)
            log.info('Auth exception for %s@%s. Try number %i...' %
                     (username, ip, count))
        except socket.error as e:
            if e[0] not in [errno.ECONNREFUSED, errno.EHOSTUNREACH, None]:
                log.exception('Exception while testing ssh access to %s:' % ip)

    out = client.ssh("test ssh access", "echo access okay", output=True)
    if "access okay" in out:
        return client
    return None
示例#2
0
def ssh_connect(ip, username, connect_kwargs={}, timeout=60):
    # HPcloud may return errno 111 for about 30 seconds after adding the IP
    for count in iterate_timeout(timeout, "ssh access"):
        try:
            client = SSHClient(ip, username, **connect_kwargs)
            break
        except socket.error, e:
            print "While testing ssh access:", e
示例#3
0
def configure_server(server, branches):
    client = SSHClient(utils.get_public_ip(server), 'jenkins')
    client.ssh('make file cache directory', 'mkdir -p ~/cache/files')
    client.ssh('make pip cache directory', 'mkdir -p ~/cache/pip')
    client.ssh(
        'install build-essential', 'sudo DEBIAN_FRONTEND=noninteractive '
        'apt-get --option "Dpkg::Options::=--force-confold"'
        ' --assume-yes install build-essential python-dev '
        'linux-headers-virtual linux-headers-`uname -r`')

    for branch_data in branches:
        if branch_data['debs']:
            client.ssh(
                'cache debs for branch %s' % branch_data['name'],
                'sudo apt-get -y -d install %s' %
                ' '.join(branch_data['debs']))

        if branch_data['pips']:
            venv = client.ssh('get temp dir for venv', 'mktemp -d').strip()
            client.ssh('create venv',
                       'virtualenv --no-site-packages %s' % venv)
            client.ssh(
                'cache pips for branch %s' % branch_data['name'],
                'source %s/bin/activate && '
                'PIP_DOWNLOAD_CACHE=~/cache/pip pip install %s' %
                (venv, ' '.join(branch_data['pips'])))
            client.ssh('remove venv', 'rm -fr %s' % venv)

        for url in branch_data['images']:
            fname = url.split('/')[-1]
            try:
                client.ssh('check for %s' % fname,
                           'ls ~/cache/files/%s' % fname)
            except:
                client.ssh('download image %s' % fname,
                           'wget -c %s -O ~/cache/files/%s' % (url, fname))

    client.ssh('clear workspace', 'rm -rf ~/workspace-cache')
    client.ssh('make workspace', 'mkdir -p ~/workspace-cache')
    for project in PROJECTS:
        sp = project.split('/')[0]
        client.ssh(
            'clone %s' % project, 'cd ~/workspace-cache && '
            'git clone https://review.openstack.org/p/%s' % project)

    script = os.environ.get('DEVSTACK_GATE_CUSTOM_SCRIPT', '')
    if script and os.path.isfile(script):
        bn = os.path.basename(script)
        client.scp(script, '/tmp/%s' % bn)
        client.ssh('run custom script %s' % bn,
                   'chmod +x /tmp/%s && /tmp/%s' % (bn, bn))

    client.ssh('sync', 'sync && sleep 5')
示例#4
0
def ssh_connect(ip, username, connect_kwargs={}, timeout=60):
    # HPcloud may return errno 111 for about 30 seconds after adding the IP
    for count in iterate_timeout(timeout, "ssh access"):
        try:
            client = SSHClient(ip, username, **connect_kwargs)
            break
        except socket.error as e:
            print "While testing ssh access:", e
            time.sleep(5)

    ret, out = client.ssh("echo access okay")
    if "access okay" in out:
        return client
    return None
示例#5
0
def openConsole(ip, username, password):
    clientIp = cgi.escape(os.environ["REMOTE_ADDR"])
    bodyContent = ""
    bodyContent += 'Your machine IP is %s <br>' % (str(clientIp))
    try:
        cl = SSHClient(clientIp)
        cl.enableSSH(ip, username)
        return {'status': 'success', 'data': 'SSH Successfull'}
    except Exception as e:
        return {
            'status':
            'error',
            'data':
            'Could not connect to remote machine. Make sure the plugin is running in your machine, Cause : %s'
            % str(e)
        }
示例#6
0
def ssh_connect(ip, username, connect_kwargs={}, timeout=60):
    if ip == 'fake':
        return fakeprovider.FakeSSHClient()
    # HPcloud may return ECONNREFUSED or EHOSTUNREACH
    # for about 30 seconds after adding the IP
    for count in iterate_timeout(timeout, "ssh access"):
        try:
            client = SSHClient(ip, username, **connect_kwargs)
            break
        except paramiko.AuthenticationException, e:
            # This covers the case where the cloud user is created
            # after sshd is up (Fedora for example)
            log.info('Password auth exception. Try number %i...' % count)
        except socket.error, e:
            if e[0] not in [errno.ECONNREFUSED, errno.EHOSTUNREACH]:
                log.exception('Exception while testing ssh access:')
示例#7
0
    def setUp(self):
        self.hostname = '127.0.0.1'
        self.user = getpass.getuser()
        self.password = '******'
        self.server = SSHServer()
        self.server.protocol = ServerProtocol

        self.port = reactor.listenTCP(0, self.server, interface=self.hostname)
        self.portnum = self.port.getHost().port

        options = {
            'hostname': self.hostname,
            'port': self.portnum,
            'user': self.user,
            'password': self.password,
            'buffersize': 32768
        }

        self.client = SSHClient(options)
        self.client.protocol = ClientProtocol
        self.client.connect()
示例#8
0
def ssh_connect(ip, username, connect_kwargs={}, timeout=60):
    if 'fake' in ip:
        return fakeprovider.FakeSSHClient()
    # HPcloud may return ECONNREFUSED or EHOSTUNREACH
    # for about 30 seconds after adding the IP
    for count in iterate_timeout(timeout, exceptions.SSHTimeoutException,
                                 "ssh access"):
        try:
            client = SSHClient(ip, username, **connect_kwargs)
            break
        except paramiko.AuthenticationException as e:
            # This covers the case where the cloud user is created
            # after sshd is up (Fedora for example)
            log.info('Auth exception for %s@%s. Try number %i...' %
                     (username, ip, count))
        except socket.error as e:
            if e[0] not in [errno.ECONNREFUSED, errno.EHOSTUNREACH, None]:
                log.exception('Exception while testing ssh access:')

    out = client.ssh("test ssh access", "echo access okay", output=True)
    if "access okay" in out:
        return client
    return None
示例#9
0
    def __init__(self,
                 mng_ip,
                 username='******',
                 password='******',
                 enable='enable',
                 password_enable='zxr10',
                 telnet_port=23,
                 ssh_port=22):
        '''
        设备初始化
        '''
        self.mng_ip = mng_ip
        self.username = username
        self.password = password
        self.enable = enable
        self.password_enable = password_enable
        self.telnet = TelnetClient()
        self.telnet_port = telnet_port
        self.ssh = SSHClient()
        self.ssh_port = ssh_port

        self.dutType = None  # 设备类型 9900 or 5960 or 其他
        self.version = None  # 版本信息
        self.snmp_enable = False
示例#10
0
logging.basicConfig(level=logging.DEBUG)
#logging.basicConfig(level=logging.INFO)
from twisted.python import log as twistedlog
observer = twistedlog.PythonLoggingObserver()
observer.start()
log = logging.getLogger('txsshclient.client')

options = {
    'hostname': '127.0.0.1',
    'port': 2222,
    'user': '******',
    'password': '******',
    'buffersize': 32768
}

client = SSHClient(options)
client.connect()


def retry():
    log.debug('retrying')
    d = client.run('sleep 5 && ls')

    def failed_or_success(result):
        if isinstance(result, failure.Failure):
            log.info("Failed %s" % (result, ))
        else:
            log.info("Success %s" % (result, ))

    d.addBoth(failed_or_success)
示例#11
0
    def __init__(self, name, namespace="default", logger_name="k8srapid"):
        self._log = logging.getLogger(logger_name)

        self._name = name
        self._namespace = namespace
        self._ssh_client = SSHClient(logger_name=logger_name)
示例#12
0
#
#Author Pradeep CH
#
__author__ = 'Pradeep CH'
__version__ = '1.0.0'

# Create instance of FieldStorage
form = cgi.FieldStorage()
clientIp = cgi.escape(os.environ["REMOTE_ADDR"])

bodyContent = ''  #html.getBackButton('/pat/ssh/remotessh.htm')

# Get mode from fields
un = form.getvalue('username')
ip = form.getvalue('ip')

if not ip or not un:
    bodyContent += 'IP and Username required.'
else:
    bodyContent += 'Your machine IP is %s <br>' % (str(clientIp))
    try:
        cl = SSHClient(clientIp)
        cl.enableSSH(ip, un)
        bodyContent += 'SSH successfull'
    except Exception as e:
        bodyContent += 'Could not connect to remote machine. Make sure the PAT plugin is running in your machine, Cause : %s' % str(
            e)
#print html
html.printHeader('Authetication Validation')
html.printBodyContent(bodyContent)