cmd = '/bin/ssh -n -q -o StrictHostKeyChecking=no root@host_ip \"/bin/nohup /bin/python /var/lib/virtdc/vmonere/host/vmonere_listener.py '+usage+' &\"'
	cmd = cmd.replace("host_ip",str(host_ip).strip())
484184
def report_usage_to_host(host_ip, vmid):
	
	#base value
	cpu_usage = 0.0
	os_mem_usage = 0.0
	task_mem_usage = 0.0
	io_usage = 0.0

	cpu_usage = get_cpu_usage()
	os_mem_usage = get_os_mem_usage()
	task_mem_usage = get_task_mem_usage()
	io_usage = get_io_usage()

	usage = str(vmid.strip())+' | '+str(cpu_usage)+' | '+str(os_mem_usage)+' | '+str(task_mem_usage)+' | '+str(io_usage)
	#usage = "'cpu |sdbfsj |sdfsdhf |sdfvsdvfgdfvj'"
	#cmd = 'python /var/lib/virtdc/vmonere/host/vmonere_listener.py '+usage
	

	''''''

	#report usage via socket
	start_client_socket(host_ip, usage)
742383
def ssh_client(host, username=None, password=None, **kwargs):
    
    client = paramiko.SSHClient()
    # save hostname and username on the instance - this is a ugly hack
    # but I don't see any other way to do that for now. Note that
    # this is only used for SshSession.__str__.
    client.hostname = host
    client.username = username
    if username is not None:
        kwargs['username'] = username
    if password is not None:
        kwargs['password'] = password
    if username is not None and password is not None:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        kwargs.setdefault('look_for_keys', False)
    client.connect(host, **kwargs)
    return client
42260
def ssh(cls, vm_id, login, identity, args=None):
        """"""
        cmd = ['ssh']
        if identity:
            cmd.extend(('-i', identity,))

        version, ip_addr = cls.vm_ip(vm_id)
        if version == 6:
            cmd.append('-6')

        if not ip_addr:
            cls.echo('No IP address found for vm %s, aborting.' % vm_id)
            return

        cmd.append('%s@%s' % (login, ip_addr,))

        if args:
            cmd.extend(args)

        cls.echo('Requesting access using: %s ...' % ' '.join(cmd))
        return cls.execute(cmd, False)
946278
def stop_accepting_passive_host_checks(self):
        
        if self.my_conf.accept_passive_host_checks:
            self.my_conf.modified_attributes |= DICT_MODATTR["MODATTR_PASSIVE_CHECKS_ENABLED"].value
            self.my_conf.accept_passive_host_checks = False
            self.my_conf.explode_global_conf()
            self.daemon.update_program_status()
667417
def dig(host):
    '''
    
    '''
    cmd = 'dig {0}'.format(salt.utils.network.sanitize_host(host))
    return __salt__['cmd.run'](cmd)
1183558
def sshagent_run(cmd):
    
    # Handle context manager modifications
    wrapped_cmd = _prefix_commands(_prefix_env_vars(cmd), 'remote')
    try:
        host, port = env.host_string.split(':')
        return local(
            u"ssh -p %s -A -o StrictHostKeyChecking=no %s@%s '%s'" % (
                port, env.user, host, wrapped_cmd
            )
        )
    except ValueError:
        return local(
            u"ssh -A -o StrictHostKeyChecking=no %s@%s '%s'" % (
                env.user, env.host_string, wrapped_cmd
            )
        )
762386
def absent(name, ip):  # pylint: disable=C0103
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    if not isinstance(ip, list):
        ip = [ip]

    comments = []
    for _ip in ip:
        if not __salt__['hosts.has_pair'](_ip, name):
            ret['result'] = True
            comments.append('Host {0} ({1}) already absent'.format(name, _ip))
        else:
            if __opts__['test']:
                comments.append('Host {0} ({1}) needs to be removed'.format(name, _ip))
            else:
                if __salt__['hosts.rm_host'](_ip, name):
                    ret['changes'] = {'host': name}
                    ret['result'] = True
                    comments.append('Removed host {0} ({1})'.format(name, _ip))
                else:
                    ret['result'] = False
                    comments.append('Failed to remove host')
    ret['comment'] = '\n'.join(comments)
    return ret
1008646
def cmd(str, print_ret=False, usr_pwd=None, run=True):
	
	if usr_pwd:
		str = 'echo {} | sudo -u {} {} '.format(usr_pwd[1], usr_pwd[0], str)

	print('  [>] {}'.format(str))

	if run:
		err, ret = commands.getstatusoutput(str)
	else:
		err = None
		ret = None

	if err:
		print('  [x] {}'.format(ret))
		raise Exception(ret)
	if ret and print_ret:
		lines = ret.split('\n')
		for line in lines:
			print('  [<] {}'.format(line))
	return ret
453964
def _main():
    ''' 
    '''
    global listener

    if len(_sys.argv) < 2 or _sys.argv[1] == '--help':
        print("Usage: %s host http_port [https_port certfile keyfile]" % \
              _sys.argv[0])
        _sys.exit(2)

    logging.basicConfig(stream=_sys.stderr, level=logging.INFO,
                        format='%(asctime)s %(levelname)s: %(message)s')

    host = _get_argv(1)
    http_port = _get_argv(2)
    https_port = _get_argv(3)
    certfile = _get_argv(4)
    keyfile = _get_argv(5)

    listener = pywbem.WBEMListener(host=host,
                                   http_port=http_port,
                                   https_port=https_port,
                                   certfile=certfile,
                                   keyfile=keyfile)

    listener.add_callback(_process_indication)
    listener.start()


    banner = """
WBEM listener started on host %s (HTTP port: %s, HTTPS port: %s).
This Python console displays any indications received by this listener as
logger outputs (Level=INFO) to the console by default.

listener: WBEMListener instance that has been started.

help(listener): Display help for using listener instance.

status() : Display count of indications received; status(reset=True) to reset
           counters

Modify logger characteristics through listener.logger:
     (ex. listener.logger.setLevel(logging.ERROR))

Ctrl-d to exit
""" % (host, http_port, https_port)

    # Determine file path of history file
    home_dir = '.'
    if 'HOME' in _os.environ:
        home_dir = _os.environ['HOME'] # Linux
    elif 'HOMEPATH' in _os.environ:
        home_dir = _os.environ['HOMEPATH'] # Windows
    histfile = '%s/.listen_history' % home_dir

    # Read previous command line history
    if _HAVE_READLINE:
        NotFoundError = getattr(__builtins__, 'FileNotFoundError', IOError)
        try:
            _readline.read_history_file(histfile)
        except NotFoundError as exc:
            if exc.errno != _errno.ENOENT:
                raise

    # Interact
    i = _code.InteractiveConsole(globals())
    i.interact(banner)

    # Save command line history
    if _HAVE_READLINE:
        _readline.write_history_file(histfile)

    return 0
930502
def virsh_per_domain_info(self,
                              **kwargs):
        '''
        
        '''
        host_list = kwargs.get('host_list', self.host_list)
        remote_user = kwargs.get('remote_user', self.remote_user)
        remote_pass = kwargs.get('remote_pass', self.remote_pass)
        sudo = kwargs.get('sudo', self.sudo)
        sudo_user = kwargs.get('sudo_user', self.sudo_user)
        sudo_pass = kwargs.get('sudo_pass', self.sudo_pass)

        result, failed_hosts = self.runner.ansible_perform_operation(
            host_list=host_list,
            remote_user=remote_user,
            remote_pass=remote_pass,
            module="command",
            module_args="virsh list",
            sudo=sudo,
            sudo_user=sudo_user,
            sudo_pass=sudo_pass)

        virsh_result = None

        fields = ["Id", "Name", "state"]

        if result['contacted'].keys():
            virsh_result = {}
            for node in result['contacted'].keys():
                nodeobj = result['contacted'][node]
                jsonoutput = rex.parse_tabular_string(nodeobj['stdout'],
                                                      fields)
                virsh_result[node] = {}
                virsh_result[node]['result'] = jsonoutput

        print virsh_result


        return virsh_result
448149
def cmd_asterix(self, args):
        ''''''
        usage = "usage: asterix <set|start|stop|restart|status>"
        if len(args) == 0:
            print(usage)
            return
        if args[0] == "set":
            self.asterix_settings.command(args[1:])
        elif args[0] == "start":
            self.start_listener()
        elif args[0] == "stop":
            self.stop_listener()
        elif args[0] == "restart":
            self.stop_listener()
            self.start_listener()
        elif args[0] == "status":
            self.print_status()
        else:
            print(usage)
823095
def dig(host):
    '''
    
    '''
    cmd = ['dig', salt.utils.network.sanitize_host(host)]
    return __salt__['cmd.run'](cmd, python_shell=False)
1248510
def remove_from_known_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False):
        
        for host in hosts:
            logger.info('[%s] Removing the remote host SSH public key from [%s]...', host.hostname, known_hosts)
            cmd = ['ssh-keygen', '-f', known_hosts, '-R', host.hostname]
            logger.debug('Call: %s', ' '.join(cmd))
            if not dry:
                try:
                    subprocess.check_call(cmd)
                except subprocess.CalledProcessError as ex:
                    logger.error(format_error(format_exception(ex)))
593210
function(command, host, options, cb) {
  let child = null;

  if(env === Constants.RESERVED.ENV_DEV) {
    child = cp.spawn(command, options);
    let prefix = command === Constants.COMMAND.SSH ? '[' + host + '] ' : '';

    child.stderr.on('data', function (chunk) {
      let msg = chunk.toString();
      process.stderr.write(msg);
      if(!!cb) {
        cb(msg);
      }
    });

    child.stdout.on('data', function (chunk) {
      let msg = prefix + chunk.toString();
      process.stdout.write(msg);
    });
  } else {
    child = cp.spawn(command, options, {detached: true, stdio: 'inherit'});
    child.unref();
  }

  child.on('exit', function (code) {
    if(code !== 0) {
      logger.warn('child process exit with error, error code: %s, executed command: %s', code,  command);
    }
    if (typeof cb === 'function') {
      cb(code === 0 ? null : code);
    }
  });
}
80956
function vhost (hostname, handle) {
  if (!hostname) {
    throw new TypeError('argument hostname is required')
  }

  if (!handle) {
    throw new TypeError('argument handle is required')
  }

  if (typeof handle !== 'function') {
    throw new TypeError('argument handle must be a function')
  }

  // create regular expression for hostname
  var regexp = hostregexp(hostname)

  return function vhost (req, res, next) {
    var vhostdata = vhostof(req, regexp)

    if (!vhostdata) {
      return next()
    }

    // populate
    req.vhost = vhostdata

    // handle
    handle(req, res, next)
  }
}
1177964
def is_ssh_available(host, opts, print_ssh_output=True):
    
    s = subprocess.Popen(
        ssh_command(opts) + ['-t', '-t', '-o', 'ConnectTimeout=3',
                             '%s@%s' % (opts.user, host), stringify_command('true')],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT  # we pipe stderr through stdout to preserve output order
    )
    cmd_output = s.communicate()[0]  # [1] is stderr, which we redirected to stdout

    if s.returncode != 0 and print_ssh_output:
        # extra leading newline is for spacing in wait_for_cluster_state()
        print(textwrap.dedent("""\n
            Warning: SSH connection error. (This could be temporary.)
            Host: {h}
            SSH return code: {r}
            SSH output: {o}
        """).format(
            h=host,
            r=s.returncode,
            o=cmd_output.strip()
        ))

    return s.returncode == 0
1223213
def main(port=8222):
    
    loop = asyncio.get_event_loop()

    # Namespace exposed in the REPL.
    environ = {'hello': 'world'}

    # Start SSH server.
    def create_server():
        return MySSHServer(lambda: environ)

    print('Listening on :%i' % port)
    print('To connect, do "ssh localhost -p %i"' % port)

    loop.run_until_complete(
        asyncssh.create_server(create_server, '', port,
                               server_host_keys=['/etc/ssh/ssh_host_dsa_key']))

    # Run eventloop.
    loop.run_forever()