def shot(conn, directory, png, rotation, *res): (w, h, depth) = res set_resolution(conn, *res) start_server(conn, rotation) sleep(0.2) if depth != 8: conn.sudo("killall qmlscene", warn=True) conn.sudo("qmlscene -platform linuxfb &> /dev/null &", pty=False) sleep(0.2) with api.connect("localhost:0") as client: client.timeout = 5 client.captureScreen(directory + "qmlscene_" + png) conn.sudo("killall qmlscene", warn=True) if depth > 1: conn.sudo("fb-test") with api.connect("localhost:0") as client: client.timeout = 5 client.captureScreen(directory + "fbtest_" + png) conn.sudo( f"python3 /vagrant/gradient.py --width {w} --height {h} --colorbit {depth}" ) with api.connect("localhost:0") as client: client.timeout = 5 client.captureScreen(directory + "gradient_" + png)
def test(): global vm global default_mode # default_mode = conf_ops.get_global_config_value('kvm', 'videoType') default_mode = conf_ops.change_global_config('vm', 'videoType', 'qxl') vm = test_stub.create_sg_vm() console = test_lib.lib_get_vm_console_address(vm.get_vm().uuid) test_util.test_logger('[vm:] %s console is on %s:%s' % (vm.get_vm().uuid, console.hostIp, console.port)) display = str(int(console.port)-5900) vm.check() vm_mode = test_lib.lib_get_vm_video_type(vm.get_vm()) if vm_mode != 'qxl': test_util.test_fail('VM is expected to work in qxl mode instead of %s' % (vm_mode)) client = api.connect(console.hostIp+":"+display) client.captureScreen('tmp.png') image = Image.open('tmp.png') if image.width != 720 or image.height != 400: test_util.test_fail("VM is expected to work in 720x400 while its %sx%s" % (image.width, image.height)) box = image.getbbox() if box != (0, 18, 403, 79) and box != (0, 18, 403, 80): test_util.test_fail("VM is expected to display text in area (0, 18, 403, 79) while it's actually: (%s, %s, %s, %s)" % (box[0], box[1], box[2], box[3])) test_util.test_logger('[vm:] change vga mode to vga=794 which is 1280x1024') cmd = 'sed -i "s/115200$/115200 vga=794/g" /boot/grub2/grub.cfg' test_lib.lib_execute_command_in_vm(vm.get_vm(), cmd) vm.reboot() vm.check() client = api.connect(console.hostIp+":"+display) client.captureScreen('tmp.png') image = Image.open('tmp.png') if image.width != 1280 or image.height != 1024: test_util.test_fail("VM is expected to work in 1280x1024 while its %sx%s" % (image.width, image.height)) box = image.getbbox() if box != (0, 18, 359, 79) and box != (0, 18, 359, 80): test_util.test_fail("VM is expected to display text in area (0, 18, 359, 79) while it's actually: (%s, %s, %s, %s)" % (box[0], box[1], box[2], box[3])) test_util.test_logger('[vm:] change vga mode to vga=907 which is 2560x1600') cmd = 'sed -i "s/vga=794/vga=907/g" /boot/grub2/grub.cfg' test_lib.lib_execute_command_in_vm(vm.get_vm(), cmd) vm.reboot() vm.check() client = api.connect(console.hostIp+":"+display) client.captureScreen('tmp.png') image = Image.open('tmp.png') if image.width != 2560 or image.height != 1600: test_util.test_fail("VM is expected to work in 2560x1600 while its %sx%s" % (image.width, image.height)) box = image.getbbox() if box != (0, 18, 359, 79) and box != (0, 18, 359, 80): test_util.test_fail("VM is expected to display text in area (0, 18, 359, 79) while it's actually: (%s, %s, %s, %s)" % (box[0], box[1], box[2], box[3])) vm.destroy() vm.check() conf_ops.change_global_config('vm', 'videoType', default_mode) test_util.test_pass('Create VM Test Success')
def test(): from vncdotool import api global vm1 global vm2 vm1 = test_stub.create_vm() vm1.check() console = test_lib.lib_get_vm_console_address(vm1.get_vm().uuid) test_util.test_logger('[vm:] %s console is on %s:%s' % (vm1.get_vm().uuid, console.hostIp, console.port)) display = str(int(console.port)-5900) test_lib.lib_set_vm_console_password(vm1.get_vm().uuid, password1) test_util.test_logger('set [vm:] %s console with password %s' % (vm1.get_vm().uuid, password1)) vm1.reboot() test_lib.lib_delete_vm_console_password(vm1.get_vm().uuid) test_util.test_logger('delete [vm:] %s console password after reboot' % (vm1.get_vm().uuid)) vm1.reboot() if not test_lib.lib_wait_target_up(console.hostIp, console.port, timeout=60): test_util.test_fail('[vm:] %s console on %s:%s is not connectable' % (vm1.get_vm().uuid, console.hostIp, console.port)) try: client = api.connect(console.hostIp+":"+display) client.keyPress('k') test_util.test_logger('[vm:] %s console on %s:%s is connectable without password' % (vm1.get_vm().uuid, console.hostIp, console.port)) except: test_util.test_fail('[vm:] %s console on %s:%s is not connectable without password' % (vm1.get_vm().uuid, console.hostIp, console.port)) vm2 = test_stub.create_vm() vm2.check() console = test_lib.lib_get_vm_console_address(vm2.get_vm().uuid) test_util.test_logger('[vm:] %s console is on %s:%s' % (vm2.get_vm().uuid, console.hostIp, console.port)) display = str(int(console.port)-5900) test_lib.lib_set_vm_console_password(vm2.get_vm().uuid, password1) test_util.test_logger('set [vm:] %s console with password %s' % (vm2.get_vm().uuid, password1)) test_lib.lib_delete_vm_console_password(vm2.get_vm().uuid) test_util.test_logger('delete [vm:] %s console password without reboot' % (vm2.get_vm().uuid)) vm1.reboot() if not test_lib.lib_wait_target_up(console.hostIp, console.port, timeout=60): test_util.test_fail('[vm:] %s console on %s:%s is not connectable' % (vm2.get_vm().uuid, console.hostIp, console.port)) try: client = api.connect(console.hostIp+":"+display) client.keyPress('k') test_util.test_logger('[vm:] %s console on %s:%s is connectable without password' % (vm2.get_vm().uuid, console.hostIp, console.port)) except: test_util.test_fail('[vm:] %s console on %s:%s is not connectable without password' % (vm2.get_vm().uuid, console.hostIp, console.port)) vm1.destroy() vm2.destroy() test_util.test_pass('Delete VM Console Password Test Success')
def test(): global vm global default_mode # default_mode = conf_ops.get_global_config_value('kvm', 'videoType') default_mode = conf_ops.change_global_config('vm', 'videoType', 'cirrus') vm = test_stub.create_sg_vm() console = test_lib.lib_get_vm_console_address(vm.get_vm().uuid) test_util.test_logger('[vm:] %s console is on %s:%s' % (vm.get_vm().uuid, console.hostIp, console.port)) display = str(int(console.port) - 5900) vm.check() vm_mode = test_lib.lib_get_vm_video_type(vm.get_vm()) if vm_mode != 'cirrus': test_util.test_fail( 'VM is expected to work in cirrus mode instead of %s' % (vm_mode)) client = api.connect(console.hostIp + ":" + display) client.captureScreen('tmp.png') image = Image.open('tmp.png') if image.width != 720 or image.height != 400: test_util.test_fail( "VM is expected to work in 720x400 while its %sx%s" % (image.width, image.height)) box = image.getbbox() if box != (0, 18, 403, 79): test_util.test_fail( "VM is expected to display text in area (0, 18, 403, 79) while it's actually: (%s, %s, %s, %s)" % (box[0], box[1], box[2], box[3])) cmd = 'sed -i "s/115200$/115200 vga=794/g" /boot/grub2/grub.cfg' test_lib.lib_execute_command_in_vm(vm.get_vm(), cmd) vm.reboot() vm.check() client = api.connect(console.hostIp + ":" + display) client.captureScreen('tmp.png') image = Image.open('tmp.png') if image.width != 1280 or image.height != 1024: test_util.test_fail( "VM is expected to work in 1280x1024 while its %sx%s" % (image.width, image.height)) box = image.getbbox() if box != (0, 18, 359, 80): test_util.test_fail( "VM is expected to display text in area (0, 18, 359, 80) while it's actually: (%s, %s, %s, %s)" % (box[0], box[1], box[2], box[3])) vm.destroy() vm.check() conf_ops.change_global_config('vm', 'videoType', default_mode) test_util.test_pass('Create VM Test Success')
def restart(self): # start menu, right for shutdown, right for context menu, up one for restart logger.debug("Selecting reboot option from start menu") self.singleKey("lsuper") self.client.pause(self.randomTime(1)) self.singleKey("right") self.client.pause(self.randomTime(1)) self.singleKey("right") self.client.pause(self.randomTime(1)) self.singleKey("up") self.client.pause(self.randomTime(1)) self.singleKey("enter") # reboot takes approx 25 seconds - disconnect first or Twisted throws a hissy fit logger.debug( "Reboot key sequence complete, disconnecting and sleeping 45 seconds..." ) self.disconnect() time.sleep(45) logger.info("Sleep finished, reconnecting and entering password") self.client = api.connect(self.address) # position for password box on 1650x1080 screen self.clickPos(797, 636) self.typestring(self.password) self.singleKey("enter") self.client.pause(self.randomTime(10))
def __init__(self): with open('config.json') as file: self.credentials = json.load(file) self.client = api.connect('192.168.8.102', self.credentials['system_password']) self.cursor_pos = (0, 0) self.client.mouseMove(*self.cursor_pos)
def main(): parser = ArgumentParser() parser.add_argument('--screenshot', action='store_true', default=False) parser.add_argument('qemu_cmd', nargs=REMAINDER) args = parser.parse_args() fifo_name = os.path.join(tempfile.mkdtemp(), 'fifo') os.mkfifo(fifo_name) try: child_args = args.qemu_cmd + ['-serial', 'pipe:' + fifo_name, '-vnc', ':0'] print('> %s' % subprocess.list2cmdline(child_args)) with Popen(child_args) as child_proc: print('[test.py] Started process %d' % child_proc.pid) try: with open(fifo_name, 'rb') as fifo: child = fdpexpect.fdspawn(fifo, encoding='utf8', logfile=sys.stdout, timeout=10) result = child.expect([r'\[kernel\] end kmain|System ready', r'\[kernel::unwind\] (.*)', pexpect.TIMEOUT]) if result == 0: print('[test.py] Success') elif result == 1: (message,) = child.match.groups() print('[test.py] Failed: %s' % message) elif result == 2: print('[test.py] Timed out') finally: if args.screenshot: client = api.connect('localhost:0', password=None) filename = 'screenshot.png' print('[test.py] Saving screenshot to %s' % filename) prev_screenshot_bytes = None if result == 0: try: with open(filename, 'rb') as f: prev_screenshot_bytes = f.read() except: pass client.captureScreen(filename) if prev_screenshot_bytes is not None: with open(filename, 'rb') as f: screenshot_bytes = f.read() if prev_screenshot_bytes != screenshot_bytes: result = 3 print('[test.py] Stopping process %d' % child_proc.pid) child_proc.kill() print('[test.py] Waiting for process %d to exit... ' % child_proc.pid, end='', flush=True) child_proc.wait() print('done') finally: os.unlink(fifo_name) return result
def test(): global vm import signal def handler(signum, frame): raise Exception() signal.signal(signal.SIGALRM, handler) signal.alarm(30) boot_option_picture = os.environ.get('bootOptionPicture') vm = test_stub.create_vm() console = test_lib.lib_get_vm_console_address(vm.get_vm().uuid) test_util.test_logger('[vm:] %s console is on %s:%s' % (vm.get_vm().uuid, console.hostIp, console.port)) display = str(int(console.port)-5900) client = api.connect(console.hostIp+":"+display) time.sleep(2) client.keyPress('esc') #client.captureRegion('/root/boot.png',0,100,600,600) client.expectRegion(boot_option_picture,0,100) test_util.test_logger('[vm:] %s support boot option' % (vm.get_vm().uuid)) # except: # test_util.test_fail('[vm:] %s is expected to support boot option' % (vm.get_vm().uuid)) vm.destroy() test_util.test_pass('Support VM Boot Option Test Success')
def test(): global vm import signal def handler(signum, frame): raise Exception() signal.signal(signal.SIGALRM, handler) signal.alarm(30) boot_option_picture = os.environ.get('bootOptionPicture') vm = test_stub.create_vm() console = test_lib.lib_get_vm_console_address(vm.get_vm().uuid) test_util.test_logger('[vm:] %s console is on %s:%s' % (vm.get_vm().uuid, console.hostIp, console.port)) display = str(int(console.port) - 5900) client = api.connect(console.hostIp + ":" + display) time.sleep(2) client.keyPress('esc') #client.captureRegion('/root/boot.png',0,100,600,600) client.expectRegion(boot_option_picture, 0, 100) test_util.test_logger('[vm:] %s support boot option' % (vm.get_vm().uuid)) # except: # test_util.test_fail('[vm:] %s is expected to support boot option' % (vm.get_vm().uuid)) vm.destroy() test_util.test_pass('Support VM Boot Option Test Success')
def test_vnc(host, password): print("Testing VNC") try: client = vncapi.connect(host, password=password) client.timeout = 5 client.keyPress('enter') except Exception as e: pass
def check_config(self): if 'server' in self.serverinfo.keys(): self.client = api.connect(self.serverinfo['server'] + ':0') self.state = True filename = 'gvnc-tmp-' + str(time.time()) + '.png' self.client.captureScreen(filename) self.write_img(filename) os.remove(filename)
def __init__(self, address, password, resolution): self.address = address self.client = api.connect(address) self.client.timeout = 10 self.x = resolution[0] self.y = resolution[1] self.pointer = (0, 0) self.password = password
def connect(host, display, password): """ Connects to the server. """ global CLIENT host = str(host) + ':' + str(display) CLIENT = api.connect(host, password)
def __init__(self, server): self.server = server self.address = server.vnc_address + ":" + server.vnc_port self.passwd = server.vnc_passwd self.connection = vncapi.connect(self.address, password=self.passwd) self.connection.keyPress('enter') print("Waiting for the installation ISO to boot...") self.connection.expectScreen('booted_install_ISO.png')
def getConnection(self): try: client = api.connect(self.vnc_server, self.passwd) print("Successully established the connection with vnc server.") except ValueError as e: print("Error While logging in to VNC Server") except Exception as e: print("Check the VNC Server Details") return client
def swiper(ips, display): passlist = [ None, 'FELDTECH_VNC', 'vnc_pcci', 'elux', 'Passwort', 'visam', 'password', 'Amx1234!', '1988', 'admin', 'Vision2', 'ADMIN', 'TOUCHLON', 'EltakoFVS', 'Wyse#123', 'muster', 'passwd11', 'qwasyx21', 'Administrator', 'ripnas', 'eyevis', 'fidel123', 'Admin#1', 'default', 'sigmatek', 'hapero', '1234', 'pass', 'raspberry', 'user', 'solarfocus', 'AVStumpfl', 'm9ff.QW', 'maryland-dstar', 'pass1', 'pass2', 'instrument', 'beijer', 'vnc', 'yesco', 'protech'] for ip in ips: print('For ip {0}'.format(ip)) for passwd in passlist: try: print('\tAttempting {0}'.format(passwd)) client = api.connect('{0}:{1}'.format(ip,display), password=passwd) client.timeout = 2 client.keyPress('enter') print(passwd) quit() except: continue print("Password not found for {0}".format(ip))
def test_server(self,ip=None,port=None,username=None,password=None): try: ip or self.ip port or self.port username or self.username password or self.password client = vncapi.connect("{}::{}".format(self.ip,self.port),password=password) client.captureScreen('screenshot.png') client.disconnect() except: pass
def __init__(self, host_ip, host_user, host_password, vnc_password='******'): self.host_ip = host_ip self.host_user = host_user self.host_password = host_password self.vnc_password = vnc_password self._set_vnc_pass() self.cli = api.connect(self.host_ip, password=self.vnc_password)
def test_color_xvnc(): with tempfile.NamedTemporaryFile(prefix="vnc_", suffix=".png") as png: with Display(backend="xvnc", rfbport=5900 + 9876): with api.connect("localhost:9876") as client: client.timeout = 1 client.captureScreen(png.name) with tempfile.NamedTemporaryFile(prefix="passwd_", delete=False) as passwd_file: password = "******" vncpasswd_generated = b"\x49\x40\x15\xf9\xa3\x5e\x8b\x22" passwd_file.write(vncpasswd_generated) passwd_file.close() with Display(backend="xvnc", rfbport=5900 + 1234, rfbauth=passwd_file.name): with api.connect("localhost:1234", password=password) as client: client.timeout = 1 client.captureScreen(png.name)
def test_color_xvnc(): with tempfile.TemporaryDirectory() as temp_dir: vnc_png = Path(temp_dir) / "vnc.png" password = "******" passwd_file = Path(temp_dir) / "pwd.txt" vncpasswd_generated = b"\x49\x40\x15\xf9\xa3\x5e\x8b\x22" passwd_file.write_bytes(vncpasswd_generated) with Display(backend="xvnc"): with api.connect("localhost:0") as client: client.timeout = 1 client.captureScreen(vnc_png) with XvncDisplay(): with api.connect("localhost:0") as client: client.timeout = 1 client.captureScreen(vnc_png) with Display(backend="xvnc", rfbport=5900 + 9876): with api.connect("localhost:9876") as client: client.timeout = 1 client.captureScreen(vnc_png) with XvncDisplay(rfbport=5900 + 9876): with api.connect("localhost:9876") as client: client.timeout = 1 client.captureScreen(vnc_png) with Display(backend="xvnc", rfbauth=passwd_file): with api.connect("localhost:0", password=password) as client: client.timeout = 1 client.captureScreen(vnc_png) with XvncDisplay(rfbauth=passwd_file): with api.connect("localhost:0", password=password) as client: client.timeout = 1 client.captureScreen(vnc_png)
def parseLine(line,number): parsedLine = line.split(" ") if parsedLine[0] == "open" and not os.path.isfile('screenshot_IP_{ip}.png'.format(ip=parsedLine[3])): #print "open at {ip}".format(ip=parsedLine[3]) try: client = api.connect('{ip}:0'.format(ip=parsedLine[3])) #print "connected" client.captureScreen('screenshot_IP_{ip}.png'.format(ip=parsedLine[3])) print "screenshot taken" with FileLock("vulnerableIPs.txt"): with open('vulnerableIPs.txt', 'a') as file: file.write(parsedLine[3]) except: pass
def __init__(self): self.docker_client = docker.from_env() try: self.container = self.docker_client.containers.run( "breandan/ubuntuvnc", ports={ '8000/tcp': 8000, '6080/tcp': 80, '5900/tcp': 5900 }, remove=True, detach=True) except: pass # Ignore error if container is already running self.vnc_client = api.connect('127.0.0.1', password=None)
def verify_password(username, ip): ip = request.args.getlist('ip').pop(0) port = request.args.getlist('port').pop(0) username = request.args.getlist('username').pop(0) auths.ip_filter(ip) auths.port_filter(port) client = api.connect('{}::{}'.format(ip, port)) user_path = app.config['MYSTATIC'].format(username) if not os.path.exists(user_path): os.makedirs(user_path) g.username = username g.ip = ip g.port = port g.userpath = user_path g.client = client return True
def parseLine(line, number): parsedLine = line.split(" ") if parsedLine[0] == "open" and not os.path.isfile( 'screenshot_IP_{ip}.png'.format(ip=parsedLine[3])): #print "open at {ip}".format(ip=parsedLine[3]) try: client = api.connect('{ip}:0'.format(ip=parsedLine[3])) #print "connected" client.captureScreen( 'screenshot_IP_{ip}.png'.format(ip=parsedLine[3])) print "screenshot taken" with FileLock("vulnerableIPs.txt"): with open('vulnerableIPs.txt', 'a') as file: file.write(parsedLine[3]) except: pass
def test_ip(args): print(f"# Testing {args.ip}") try: with api.connect(args.ip, password=args.password) as client: client.timeout = args.timeout try: client.refreshScreen() screenshot_file = os.path.join(args.screendir, args.ip + '.png') client.captureScreen(screenshot_file) print(f"Successfully captured screenshot: {screenshot_file}") except Exception as e: print(e) client.disconnect() except Exception as e: print(e)
def __synchronize_backend(self, backend=None, category="vncdotool", reset=False): if category != "vncdotool": raise UnsupportedBackendError( "Backend category '%s' is not supported" % category) if reset: super(VNCDoToolController, self).synchronize_backend("vncdotool", reset=True) if backend is not None and self.params[category]["backend"] != backend: raise UninitializedBackendError( "Backend '%s' has not been configured yet" % backend) from vncdotool import api if self._backend_obj: # api.connect() gives us a threaded client, so we need to clean up resources # to avoid dangling connections and deadlocks if synchronizing more than once self._backend_obj.disconnect() self._backend_obj = api.connect( '%s:%i' % (self.params[category]["vnc_hostname"], self.params[category]["vnc_port"]), self.params[category]["vnc_password"]) # for special characters preprocessing for the vncdotool self._backend_obj.factory.force_caps = True # additional logging for vncdotool available so let's make use of it logging.getLogger('vncdotool.client').setLevel(10) logging.getLogger('vncdotool').setLevel(logging.ERROR) logging.getLogger('twisted').setLevel(logging.ERROR) # screen size with NamedTemporaryFile(prefix='guibot', suffix='.png') as f: filename = f.name screen = self._backend_obj.captureScreen(filename) os.unlink(filename) self._width = screen.width self._height = screen.height # sync pointer self.mouse_move(Location(self._width, self._height), smooth=False) self.mouse_move(Location(0, 0), smooth=False) self._pointer = Location(0, 0) self._keymap = inputmap.VNCDoToolKey() self._modmap = inputmap.VNCDoToolKeyModifier() self._mousemap = inputmap.VNCDoToolMouseButton()
def test(): global test_obj_dict global vm import signal def handler(signum, frame): raise Exception() signal.signal(signal.SIGALRM, handler) signal.alarm(300) test_util.test_dsc('Create test clone windows vm boot option') image_name = os.environ.get('imageName_windows') vm = test_stub.create_vm(image_name=image_name) test_obj_dict.add_vm(vm) backup_storage_list = test_lib.lib_get_backup_storage_list_by_vm(vm.vm) for bs in backup_storage_list: if bs.type in [ inventory.IMAGE_STORE_BACKUP_STORAGE_TYPE, inventory.CEPH_BACKUP_STORAGE_TYPE ]: break else: vm.destroy() test_util.test_skip( 'Not find image store or ceph type backup storage.') new_vm = vm.clone(vm_name)[0] test_obj_dict.add_vm(new_vm) console = test_lib.lib_get_vm_console_address(new_vm.get_vm().uuid) test_util.test_logger('[vm:] %s console is on %s:%s' % (new_vm.get_vm().uuid, console.hostIp, console.port)) display = str(int(console.port) - 5900) client = api.connect(console.hostIp + ":" + display) client.keyPress('esc') time.sleep(2) client.expectRegion(boot_option_picture, 0, 100) vm.destroy() new_vm.destroy() test_util.test_pass('VM With Volumes Boot Option Test Success')
def record(output, host, fps, password=None): print("Start Recording") pid = 0 retval = 0 cli = api.connect(host, password=password) cli.refreshScreen(False) videodims = cli.screen.size fourcc = cv2.VideoWriter_fourcc(*'mp4v') frame = int(fps) video = cv2.VideoWriter(output, fourcc, frame, videodims) p_start = time.time() try: def sigint_handler(sig, frame): raise KeyboardInterrupt signal.signal(signal.SIGINT, sigint_handler) try: while 1: elapse = int() start = time.time() for i in range(0, frame): cli.refreshScreen(False) imtemp = cli.screen.copy() video.write( cv2.cvtColor(np.array(imtemp), cv2.COLOR_RGB2BGR)) stop = time.time() elapse = stop - start print("Frame Process : " + str(elapse)) if elapse < 1: time.sleep(1 - elapse) finally: p_stop = time.time() print(p_stop - p_start) video.release() cli.disconnect() print("Stop Recording") except KeyboardInterrupt: pass if pid: os.killpg(os.getpgid(pid), signal.SIGTERM) return retval
def screenshotGet(datas, timeout, screenshotDir, includeBlackScreens): try: #create snapshot dir saveDir = os.path.join(os.path.dirname(os.path.realpath(__file__)), screenshotDir) if os.path.isdir(saveDir): pass else: os.mkdir(saveDir) except OSError: print("Screenshot: Failed to create dir") return False print(f"Screenshot: Saving screenshots in {screenshotDir} directory..") for data in datas: for proto in data["protocols"]: protocol = re.search(portRawRe, proto).group(1) try: client = api.connect(f"{data['ip']}::{protocol}", password=None) client.timeout = timeout + 0.5 client.keyPress('enter') sleep(0.5) #for the enter key press to have some effect maybe imgDir = os.path.join(saveDir, f"{data['ip']}:{protocol}.jpg") client.captureScreen(imgDir) if not includeBlackScreens: image = imread(imgDir, 0) if countNonZero(image) == 0: os.remove(imgDir) print( f"Screenshot: Black for {data['ip']}:{protocol}, removing.." ) continue except TimeoutError: print( f"Screenshot: Timeout for {data['ip']}:{protocol}, skipping.." ) continue except: print( f"Screenshot: Error for {data['ip']}:{protocol}, skipping.." ) continue print(f"Screenshot: Done for {data['ip']}:{protocol}")
def screenShot(ipAddress, port): connect_string = ipAddress + '::' + port print(connect_string) filename = 'RESULTS/' + ipAddress + '_' + port + '.png' try: client = api.connect(connect_string, password=None) client.timeout = 30 except: print('Connect Failed') return try: print("Attempting screen capture") client.captureScreen(filename) print("SUCCESS") except: print('Timed out') shutil.copy('DEFAULT.png', filename) client.disconnect() print("Disconnecting Client") client.disconnect()
def Target(task): userpath = request.cookies.get('userpath') ip = request.cookies.get('ip') port = request.cookies.get('port') client = api.connect('{}::{}'.format(ip, port)) auths.client = client if task == 'chongbo': commands = eval(request.form['data']) if auths.produce_vdo(commands=commands, userpath=userpath): vdo_path = userpath + '/command.vdo' try: auths.allocate_vncvdo(vdo_path) except Exception as e: auths.response_filter(0) else: auths.client_screen(userpath) return 'success' else: auths.response_filter(0) else: auths.response_filter(1)
def test(): global test_obj_dict global vm import signal def handler(signum, frame): raise Exception() signal.signal(signal.SIGALRM, handler) signal.alarm(30) test_util.test_dsc('Create test vm with 2 additional data volumes boot option') conf_ops.change_global_config('vm', 'bootMenu', 'false') disk_offering = test_lib.lib_get_disk_offering_by_name(os.environ.get('smallDiskOfferingName')) disk_offering_uuids = [disk_offering.uuid] disk_offering = test_lib.lib_get_disk_offering_by_name(os.environ.get('rootDiskOfferingName')) disk_offering_uuids.append(disk_offering.uuid) vm = test_stub.create_vm_with_volume(data_volume_uuids = disk_offering_uuids) test_obj_dict.add_vm(vm) vm_inv = vm.get_vm() vm_ip = vm_inv.vmNics[0].ip console = test_lib.lib_get_vm_console_address(vm.get_vm().uuid) test_util.test_logger('[vm:] %s console is on %s:%s' % (vm.get_vm().uuid, console.hostIp, console.port)) display = str(int(console.port)-5900) client = api.connect(console.hostIp+":"+display) time.sleep(2) client.keyPress('esc') try: client.expectRegion(boot_option_picture,0,100) except: test_util.test_logger('Success to not enable boot menu.') else: test_util.test_fail('Fail to not enable boot menu.') vm.destroy() test_util.test_pass('VM With Volumes Boot Option Test Success')
def __init__(self, display, password=None, delay=.1): self._vnc = api.connect(display, password=password) self.color = 0xc # what color our cursor is self.cursor_pos = (160, 100) # where our cursor is self.delay = delay
client.pause(1) client.mousePress(1) for i in range(2): client.keyPress('lctrl-l') client.pause(0.5) def log_in(dummy1, dummy2): #must wait 30-40 sec for pc to boot # for i in range(2): client.keyPress('enter') client.pause(1) for i in "1556": client.keyPress(i) #must wait at least 10 sec for pc to log in def turn_off(dummy1, dummy2): client.pause(1) client.keyPress('ctrl-alt-del') client.pause(1) client.mouseMove(1860,1020) client.mousePress(1) client.pause(0.5) client.mouseMove(1860,960) client.mousePress(1) client.pause(1) if __name__ == '__main__': client = api.connect("192.168.1.20") option = {"log_in":log_in, "turn_off":turn_off, "music":music} option[sys.argv[1]](sys.argv[2], sys.argv[3]) sys.exit()
def test(): from vncdotool import api global vm session_uuid = None instance_offering_uuid = test_lib.lib_get_instance_offering_by_name(os.environ.get('instanceOfferingName_s')).uuid cond = res_ops.gen_query_conditions('mediaType', '!=', 'ISO') cond = res_ops.gen_query_conditions('platform', '=', 'Linux', cond) image_uuid = res_ops.query_resource(res_ops.IMAGE, cond, session_uuid)[0].uuid l3net_uuid = res_ops.get_resource(res_ops.L3_NETWORK, session_uuid)[0].uuid vm_creation_option = test_util.VmOption() vm_creation_option.set_instance_offering_uuid(instance_offering_uuid) vm_creation_option.set_image_uuid(image_uuid) vm_creation_option.set_l3_uuids([l3net_uuid]) vm_creation_option.set_console_password(password1) vm = test_vm.ZstackTestVm() vm.set_creation_option(vm_creation_option) vm.create() vm.check() console = test_lib.lib_get_vm_console_address(vm.get_vm().uuid) test_util.test_logger('[vm:] %s console is on %s:%s' % (vm.get_vm().uuid, console.hostIp, console.port)) display = str(int(console.port)-5900) try: client = api.connect(console.hostIp+":"+display) client.keyPress('k') test_util.test_fail('[vm:] %s console on %s:%s is connectable without password' % (vm.get_vm().uuid, console.hostIp, console.port)) except: test_util.test_logger('[vm:] %s console on %s:%s is not connectable without password' % (vm.get_vm().uuid, console.hostIp, console.port)) try: client = api.connect(console.hostIp+":"+display, password1) client.keyPress('k') test_util.test_logger('[vm:] %s console on %s:%s is connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password1)) except: test_util.test_fail('[vm:] %s console on %s:%s is not connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password1)) test_lib.lib_set_vm_console_password(vm.get_vm().uuid, password2) test_util.test_logger('set [vm:] %s console with password %s' % (vm.get_vm().uuid, password2)) vm.reboot() try: client = api.connect(console.hostIp+":"+display, password2) client.keyPress('k') test_util.test_logger('[vm:] %s console on %s:%s is connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password2)) except: test_util.test_fail('[vm:] %s console on %s:%s is not connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password2)) import signal def handler(signum, frame): raise Exception() signal.signal(signal.SIGALRM, handler) signal.alarm(30) try: client = api.connect(console.hostIp+":"+display, password1) client.keyPress('k') test_util.test_fail('[vm:] %s console on %s:%s is connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password1)) except: test_util.test_logger('[vm:] %s console on %s:%s is not connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password1)) vm.destroy() test_util.test_pass('Set VM Console Password Test Success')
from vncdotool import api from reader import * import time from threading import Thread from solver import * from grid import * client = api.connect('localhost:1', 'vnc') f = 'working.png' tl = get_grid(f) b = get_box(f)[0] def translate(x, y): x = (b//2) + (b * x) y = (b//2) + (b * y) x = x + tl[0] y = y + tl[1] return x, y def mouseDrag2(client, start, dest, step): """ Move the mouse point to position (x, y) in increments of step """ sx, sy = start x, y = dest if x < sx: xsteps = [sx - i for i in xrange(step, sx - x + 1, step)] else: xsteps = xrange(sx, x, step) if y < sy:
def connect_to_vnc_server(self, server, port=5900): self._client = api.connect('{0}::{1}'.format(server, port)) self._server = server self._port = port
def showvnc(self, host, display, password=None, rotate=None, invert=False, sleep=1, full_interval=100): with api.connect(':'.join([host, display]), password=password) as client: previous_vnc_image = None diff_bbox = None # number of updates; when it's 0, do a full refresh updates = 0 client.timeout = 30 while True: try: client.refreshScreen() except TimeoutError: print("Timeout to server {}:{}".format(host, display)) client.disconnect() sys.exit(1) new_vnc_image = client.screen # apply rotation if any if rotate: new_vnc_image = new_vnc_image.rotate(rotate, expand=True) # apply invert if invert: new_vnc_image = ImageOps.invert(new_vnc_image) # rescale image if needed if new_vnc_image.size != (self.driver.width, self.driver.height): new_vnc_image = new_vnc_image.resize( (self.driver.width, self.driver.height)) # if at least two frames have been processed, get a bounding box of their difference region if new_vnc_image and previous_vnc_image: diff_bbox = self.band( self.img_diff(new_vnc_image, previous_vnc_image)) # frames differ, so we should update the display if diff_bbox: # increment update counter updates = (updates + 1) % full_interval # if partial update is supported and it's not time for a full refresh, # draw just the different region if updates > 0 and (self.driver.supports_partial and self.partial): print("partial ({}): {}".format(updates, diff_bbox)) self.driver.draw(diff_bbox[0], diff_bbox[1], new_vnc_image.crop(diff_bbox)) # if partial update is not possible or desired, do a full refresh else: print("full ({}): {}".format(updates, new_vnc_image.size)) self.driver.draw(0, 0, new_vnc_image) # otherwise this is the first frame, so run a full refresh to get things going else: if updates == 0: updates = (updates + 1) % full_interval print("initial ({}): {}".format( updates, new_vnc_image.size)) self.driver.draw(0, 0, new_vnc_image) previous_vnc_image = new_vnc_image.copy() time.sleep(float(sleep))
def test(): from vncdotool import api global vm vm = test_stub.create_vm() vm.check() console = test_lib.lib_get_vm_console_address(vm.get_vm().uuid) test_util.test_logger('[vm:] %s console is on %s:%s' % (vm.get_vm().uuid, console.hostIp, console.port)) display = str(int(console.port)-5900) try: client = api.connect(console.hostIp+":"+display) client.keyPress('k') test_util.test_logger('[vm:] %s console on %s:%s is connectable without password' % (vm.get_vm().uuid, console.hostIp, console.port)) except: test_util.test_fail('[vm:] %s console on %s:%s is not connectable without password' % (vm.get_vm().uuid, console.hostIp, console.port)) test_lib.lib_set_vm_console_password(vm.get_vm().uuid, password1) test_util.test_logger('set [vm:] %s console with password %s' % (vm.get_vm().uuid, password1)) vm.reboot() try: client = api.connect(console.hostIp+":"+display) client.keyPress('k') test_util.test_fail('[vm:] %s console on %s:%s is connectable without password' % (vm.get_vm().uuid, console.hostIp, console.port)) except: test_util.test_logger('[vm:] %s console on %s:%s is not connectable without password' % (vm.get_vm().uuid, console.hostIp, console.port)) try: client = api.connect(console.hostIp+":"+display, password1) client.keyPress('k') test_util.test_logger('[vm:] %s console on %s:%s is connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password1)) except: test_util.test_fail('[vm:] %s console on %s:%s is not connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password1)) test_lib.lib_set_vm_console_password(vm.get_vm().uuid, password2) test_util.test_logger('set [vm:] %s console with password %s' % (vm.get_vm().uuid, password2)) vm.reboot() try: client = api.connect(console.hostIp+":"+display, password2) client.keyPress('k') test_util.test_logger('[vm:] %s console on %s:%s is connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password2)) except: test_util.test_fail('[vm:] %s console on %s:%s is not connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password2)) import signal def handler(signum, frame): raise Exception() signal.signal(signal.SIGALRM, handler) signal.alarm(30) try: client = api.connect(console.hostIp+":"+display, password1) client.keyPress('k') test_util.test_fail('[vm:] %s console on %s:%s is connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password1)) except: test_util.test_logger('[vm:] %s console on %s:%s is not connectable with password %s' % (vm.get_vm().uuid, console.hostIp, console.port, password1)) vm.destroy() test_util.test_pass('Set VM Console Password Test Success')