首页 文章 精选 留言 我的

精选列表

搜索[诊断自动化],共10000篇文章
优秀的个人博客,低调大师

Ansible自动化运维工具阐述及配置实现

什么是ansible ansible是一个轻量级的运维管理工具 , 基于Python研发 。可实现对系统的批量管理配置、程序的批量部署、批量的运行命令等功能。 仅需在任意管理主机安装 ansible 程序即可实现批量管理被管控主机且被管控的主机无需客户端。 我们在安装ansible时一定要依托epel源来安装(推荐阿里云),并且在线用yum安装。它基于python开发所以得解决ansible对python编程的各种依赖。 ansible 特性 1、模块化:调用特定的模块,完成特定的任务;2、基于Python语言研发主要模块由Paramiko, PyYAML和Jinja2三个核心库实现;3、部署简单:agentless;4、支持自定义模块,使用任意编程语言;5、强大的playbook机制;6、具有幂等性; ansible 基本架构 Modules:模块化Core Modules 核心模块Customed Modules 自定义模块Host Iventory 主机库清单,定义要管理的主机Files 可以通过配置文件来实现CMDB 也可以通过外部存储来实现PlayBooks 剧本,定义每个主机所扮演的角色Hosts 哪些主机Roles 哪些角色Connection Plugins:连接插件,主要连接各管控主机EmailLogginOther 注意,ansible不是服务!千万也不用去想服务的概念 安装及程序环境:程序:ansibleansible-playbookansible-doc配置文件:/etc/ansible/ansible.cfg主机清单:/etc/ansible/hosts插件目录:/usr/share/ansible_plugins/ 主机清单说明 vim/etc/ansible/hosts #Ex1:Ungroupedhosts,specifybeforeanygroupheaders. 直接给出主机,IP主机名都可以 ##green.example.com ##blue.example.com ##192.168.100.1 ##192.168.100.10 #Ex2:Acollectionofhostsbelongingtothe'webservers'group 把几个主机分组,用中括号定义组名 ##[webservers] ##alpha.example.org... ##192.168.1.100... #Ifyouhavemultiplehostsfollowingapatternyoucanspecify 对主机进行通配001:006表示到一个范围 ##www[001:006].example.com #Ex3:Acollectionofdatabaseserversinthe'dbservers'group 定义一组数据库服务器 ##[dbservers] ##db02.intranet.mydomain.net... ##10.25.1.56... 基本使用入门,获取模块列表 ansible-doc-l获取模块列表 ansible-doc-sMOD_NAME获取指定模块帮助信息 以ping模块为例,测试 [root@localhost~]#ansiblewebserver-mping//我是定义了webserver组 172.16.5.103|UNREACHABLE!=>{ "changed":false, "msg":"Failedtoconnecttothehostviassh.", "unreachable":true } 172.16.5.102|UNREACHABLE!=>{ "changed":false, "msg":"Failedtoconnecttothehostviassh.", "unreachable":true } 以上的测试结果提示没有通过ssh连接到主机,所以我们得配置基于ssh的公钥认证 因为ansible是基于ssh进行认证的 也可以这样:ansibleall-mping--ask-pass-cparamiko//你懂的 设置 SSH 公钥认证,并把生成的公钥拷贝到任意N个主机,实现无密码操作 在Ansible服务端生成密钥,并且复制公钥到节点中。 root@ansible~]#ssh-keygen//一路回车,文件生成路径root/.ssh/ 使用ssh-copy-id命令来复制Ansible公钥到节点中。 ssh-copy-id-iroot@172.16.5.102/103/105 以ping模块再次测试 [root@Centos6~]#ansibleall-mping 172.16.5.103|SUCCESS=>{ "changed":false, "ping":"pong" } 172.16.5.102|SUCCESS=>{ "changed":false, "ping":"pong" } 172.16.5.105|SUCCESS=>{ "changed":false, "ping":"pong" } [root@Centos6~]# ok成功...... 常用模块举例说明1 常用模块: ping:探测目标主机是否存活; 举例:ansibleall-mping command:在远程主机执行命令; 举例:ansibleall-mcommand-a"ifconfig" 举例:ansibleall-mcommand-a"useraddcentos" shell:在远程主机上调用shell解释器运行命令,支持shell的各种功能,如管道等 举例:ansibleall-mshell-a"echocentos|passwd--stdincentos" copy:复制文件,给定内容生成文件,mode,owner,group,follow,... 拷贝文件 举例:ansibleall-mcopy-a"src=/etc/fstabdest=/tmp/fstab.ansiblemode=640" 生成文件 举例:ansibleall-mcopy-a"content='hell\nworld\n'dest=/tmp/fstab.ansiblemode=640" file:设置文件属性 更改文件属主 举例:ansibleall-mfile-a"path=/tmp/fstab.ansibleowner=centos" 删除文件 举例:ansibleall-mfile-a"path=/tmp/fstab.ansiblestate=absent" state用来定义目标文件状态的 创建指定文件空目录 举例:ansibleall-mfile-a"path=/tmp/dir.ansiblestate=directory" 链接文件 举例:ansibleall-mfile-a"path=/tmp/test.ansible.linksrc=/tmp/test.ansible state=link" fetch:从远程主机拉取一个文件 ansible是用来管理多节点的,从远程拉取多个文件到目标主机显然不近乎仁义。所以用scp就能搞定。略过 常用模块举例说明2 cron:用来管理crontab的周期性任务 定义一个任务 举例:ansibleall-mcron-a"minute'*/5'job='/usr/sbin/ntpdate10.1.0.1&>/dev/null' name='synctime'" crontab-l 删除一个任务 举例:ansibleall-mcron-a"name='synctime'state=absent" 只删除用ansible定义的名 hostname:定义主机名 举例: yum:使用yum包管理器,完成程序包管理 举例:ansibleall-myum-a"name=httpd"安装 举例:ansibleall-myum-a"name=httpdstate=absent"删除 service:控制服务,控制服务是否开机自动启动 举例:ansibleall-mservice-a"name=httpdstate=startedenbaled=true" group:添加或者删除组 举例: user:管理组账号 举例: setup:收集远程各主机的各种属性之和 举例:ansibleall-msetup 以上内容就到这里,我们该定义一个剧本了 定义一个PlayBook,我们来唱剧本 playbook是由一个或多个”play”组成的列表。play的主要功能在于将事先归为一组的主机装扮成事先通过ansible中的task定义好的角色。从根本上来将,所谓的task无非是调用ansible的一个module。将多个paly组织在一个playbook中,即可以让他们联通起来按事先编排的机制同唱一台大戏。YAML是用来写配置文件的,接下来的配置文件都是以yaml为后缀 [root@Centos6~]#yuminfoPyYAML 核心元素: Tasks:任务,由模块定义的操作的列表; Variables:变量 Templates:模板,即使用了模板语法的文本文件; Handlers:由特定条件触发的Tasks; Roles:角色;自包含,有完整独立实体 playbook的基础组件: Hosts:运行指定任务的目标主机,可多个; remote_user:在远程主机以哪个用户身份执行; sudo_user:非管理员需要拥有sudo权限; tasks:给出任务列表,执行完一个,执行第二个 模块,模块参数: 格式: (1)action:modulearguments//任务执行过程 (2)modulename:arguments//指定运行的模块 示例;利用playbook指挥三台主机都创建mygrp组 [root@Centos6~]#vimgroup.yaml -hosts:all//任务运行在所有主机 remote_user:root//在远程主机以哪个用户执行 tasks://任务列表1 -name:installagroup//任务名 group:name=mygrpsystem=true//调用group模块创建组mygrp -name:installauser//任务名 user:name=user1group=mygrpsystem=true//创建user1组mygrp -hosts:webserver//任务运行在webserver组内的主机 remote_user:root//在远程主机以哪个用户执行 tasks://任务列表2 -name:installhttpdpackage//任务名 yum:name=httpd//调用yum模块安装httpd -name:starthttpdservice//任务名 service:name=httpdstate=started//调用service模块启动服务 检查语法,测试运行 annsible-playbook--syntax-checkgroup.yaml annsible-playbook--list-hosts--list-tasksgroup.yaml 示例;利用playbook指挥webserver组内主机安装httpd并监听8080端口 vimhttpd.yaml -hosts:webserver remote_user:root tasks: -name:installhttpdpackage yum:name=httpdstate=latest tags:installpkg//指明跑某个标签-tinstallpkg -name:installconffile copy:src=/root/httpd.confdest=/etc/httpd/conf/httpd.conf tags:installconf//指明跑某个标签-tinstallconf notify:restarthttpdservice通知给《===httpd -name:starthttpdservice service:name=httpdstate=started handlers://处理器,也是任务,但是在一定条件下触发 -name:restarthttpdservice//handlers名字 service:name=httpdstate=restarted 语法检查,测试运行 annsible-playbook--syntax-check-tinstallconf--list-tagshttpd.yaml annsible-playbook--syntax-checkhttpd.yaml annsible-playbook--list-hosts--list-taskshttpd.yaml 注意:handlers:是指在一定条件下触发,指明在一个需要让别人重启服务才生效的任务上使用notify,通知一定是handlers名字tags:只执行playbook中指定的tags标签,满足部分需要,多个任务可指明一个同tags也可以一次调用两个标签,如下annsible-playbook -t installconf,installpkg httpd.yaml 自定义变量Variables,可自定义安装任意程序包 [root@Centos6~]#catname.yaml -hosts:webserver remote_user:root vars: -pkgname:memcached//playbook中使用的变量Variables tasks: -name:installapackage yum:name=`pakgname`state=present//自定义变量 [root@Centos6~]# 语法测试 ansible-playbook--syntax-checkname.yaml ansible-playbook-epkgname=httpd/vsftpd/name.yaml 注意:在执行时命令行中给出的值要优先于playbook内置变量 如:ansible-playbook-epkgname=httpdname.yaml 检查:rpm-qlhttpdmemcached 传递给主机单独变量,实现某些主机安装不同程序包 编辑主机清单在每个主机后面指定调用变量并赋值 vim/etc/ansible/hosts [webserver] 172.16.5.102pkgname=nginx 172.16.5.103pkgname=httpd [webserver:vars]//为一个组内不同主机定义相同变量,效果同上 webserver组内有一组变量vars,其中变量名是pkgname值是memcached pkgname=memcached vimname.yaml -hosts:webserver remote_user:root tasks: -name:installapackage yum:name=`pkgname`state=present 语法测试 ansible-playbook--syntax-checkname.yaml Inventory还可以使用参数:用于定义ansible远程连接目标主机使用的属性,而非传递给playbook的变量如: [webserver]172.16.5.102 ansible_ssh_user= ansible_ssh_pass ansible_sudo_pass不再是传递给playbook变量,而是主机本身。 playbook模版 模版本身是文本文件,内部嵌套有模板语言脚本(使用模板语言编写jinjia2)Jinja2 是仿照 Django 模板的 Python 模板语言。 它速度快,被广泛使用,并且提供了可选的沙箱模板执行环境保证安全。只介绍简单使用,不过多阐述,语言啊jinjia2是用来写模版文件的,接下来的模版文件都是以j2为后缀 语法格式: 支持字面量: 字符串:使用单引号或双引号; 数字:整数、浮点数; 列表:[item1,item2,...] 元组:(item1,item2,...) 字典:{key1:value1,key2:value2,...} 布尔型:true/false 算术运算:+,-,*,/,//,%,** 比较操作:==,!=,>,<,>=,<= 逻辑运算:and,or,not 基于模版把nginx配置文件对应的虚拟cpu值改成不是auto 安装nginx程序包,我们要使用nginx的配置文件当模版yum install nginxcp /etc/nginx/nginx.conf .vim nginx.confworker_processes ` ansible_processor_vcpus `; //由auto改成这样vim nginx.yaml– hosts: webserverremote_user: roottasks:– name: copy a nginx filetemplate: src=/root/nginx.conf dest=/tmp/nginx.conf语法测试ansible-playbook –syntax-check nginx.yaml 完整安装nginx程序,并调用nginx.conf.j2模版 vim nginx.yaml– hosts: nginxserver //指定组remote_user: roottasks:– name: install nginx package //安装nginx程序包yum: name=nginx state=latest //调用的yum模块– name: install conf filetemplate: src=/root/nginx.conf.j2 dest=/etc/nginx.conf //调用的配置文件模版tags: ngxconf //标签notfiy: reload nginx service //通知让标签干什么– name: start nginx serviceservice: name=nginx state=started enabled=true //启动服务,并开机启动handlers: //触发器,当某个条件满足时将触发,也是任务– name: reload nginx serviceshell: /usr/sbin/nginx -s reload语法测试ansible-playbook –syntax-check nginx.yaml 使用when条件判断语句,判断基于不同发行版使用不同命令来重启nginx服务 vimnginx2.yaml -hosts:all remote_user:root tasks: -name:installnginxpackage yum:name=nginxstate=latest -name:startnginxserviceonCentOS6 shell:servicenginxstart when:ansible_distribution=="CentOS"andansible_distribution_major_version=="6" -name:startnginxservice shell:systemctlstartnginx.service when:ansible_distribution=="CentOS"andansible_distribution_major_version=="7" 语法测试 ansible-playbook--syntax-checknginx2.yaml 基于字符串列表给出元素循环:迭代,需要重复执行的任务;对迭代项的引用,固定变量名为”item”,使用with_item属性给定要迭代的元素;元素列表有两种:字符串,字典 vimweb.yaml -hosts:webserver remote_user:root tasks: -name:installpackage yum:name=`item`state=latest with_items: -httpd -php -php-mysql -php-mbstring -php-gd 语法测试 ansible-playbook--syntax-checkweb.yaml 基于字典列表给出元素循环:迭代,需要重复执行的任务;之前我们讲过我们要批量在组内的机器上创建用户是可以的。无非调用user模块并指明组就可以,但是在不同组内的机器上创建的,可能用户名与组名都是不相同的,那我们想要它都同样该怎么办呢?这个时候我们就可以通过固定变量item来实现 增加两条name,一个指明用户,一个指明组名 vimcreat.yaml -hosts:webserver remote_user:root tasks: -name:creatgroups//第一个任务 yum:name=`item`state=latest with_items: -groupx1 -groupx2 -groupx3 -name:creatusers//第二个任务 user:name={{item.name}}group={{item.group}}state=present with_items://元素列表 -{name:'userx1',group:'groupx1'}//name键值队 -{name:'userx1',group:'groupx1'}//name键值队 -{name:'userx1',group:'groupx1'}//name键值队 语法测试:ansible-playbook--checkcreat.yaml 注释: item.name表示调用第一个键name里的值userx1 item.group表示调用第一个键group里的值groupx1 角色(自包含,按照目录结构来组织) 指定由哪些主机去对应的完成哪个已定义好的角色 roles是以特定的层级目录结构进行组织的tasks、variables、handlers、templates…role_name/files/:存储由copy或script等模块调用的文件;tasks/:此目录中至少应该有一个名为main.yml的文件,用于定义各task;其它的文件需要由main.yml进行“包含”调用;handlers/:此目录中至少应该有一个名为main.yml的文件,用于定义各handler;其它的文件需要由main.yml进行“包含”调用;vars/:此目录中至少应该有一个名为main.yml的文件,用于定义各variable;其它的文件需要由main.yml进行“包含”调用;templates/:存储由template模块调用的模板文本;meta/:此目录中至少应有一个名为main.yml文件,定义当前角色的特殊设定及其依赖关系;其它文件需要由main.yml进行“包含”调用;default/:此目录中至少应该有一个名为main.yml的文件,用于设定默认变量; 举例:在webserver组内机器分别各自安装nginx,memcached,msql-server通过roles调用tasks创建目录mkdir -pv ./{nginx,memcached,httpd,mysql}/{files,templates,vars,handlers,meta,tasks,default} 安装nginx 1、在nginx目录tasks目录下创建main.yml文件 [root@Centos6tasks]#vimmain.yml -name:copynginxpackagetoremotehost//先拷贝安装程序 copy:src=nginx-1.10.1-1.el7.x86_64.rpm dest=/tmp/nginx-nginx-1.10.1-1.el7.x86_64.rpm tags:cppkg -name:installnginxpackage//再安装程序包 yum:name=/tmp/nginx-1.10.0-1.el7.nginx.x86_64.rpmstate=present -name:installconffilenginx.conf//然后提供配置文件 template:src=nginx.conf.j2dest=/etc/nginx/nginx.conf tags:nginxconf//加了一个标签,按需执行 notify:reloadnginxservice//通知标签要干什么,我们需要在handlers目录下创建触发器 -name:installconffiledefault.conf//再提供nginx默认文件 template:src=default.conf.j2dest=/etc/nginx/conf.d/default.conf tags:nginxconf notify:reloadnginxservice -name:startnginixservice//启动服务 service:name=nginxenabled=truestate=started 2、在nginx目录handlers目录下创建main.yml文件 [root@Centos6handlers]#catmain.yml -name:reloadnginxservice service:name=nginxstate=restarted [root@Centos6handlers]# 3、拷贝nginx.conf文件到templates目录下做模版 [root@Centos6roles]#cp/etc/nginx/nginx.confnginx/templates/nginx.conf.j2 更改worker_processes`ansible_processor_vcps`; 4、拷贝default.conf文件到templates目录下做模版 [root@Centos6roles]#cp/etc/nginx/conf.d/default.confnginx/default/default.conf.j2 更改listen`nginxport`;//变量定义 5、nginx/vars目录下创建main.yml调用变量 写入nginxport:"8090" 6、在ansible目录下创建nginx.yml文件来调用以上各种组织好的nginx角色 [root@Centos6roles]#vimnginx.yml -hosts:webserver remote_user:root roles://定义角色 -{role:nginx,ngxport:8080}//即能调角色,又能向角色传变量 -nginx//角色调用 7、编辑ansible.cfg文件启用roles_path让roles去找所定义的文件 [root@Centos6ansible]#vimansible.cfg 启用把前面注释去掉roles_path=/etc/ansible/roles 8、要注意,避免错误,最好定义好文件后各自做个语法测试 9、然后就可以让剧本跑一遍了 10、确保你的系统selinux是disabled,不然服务起不来 ansible-playbook--syntax-checknginx.yml 安装memcached [root@Centos6memcached]#ls../memcached/* ../memcached/handlers: main.yml -name:reloadmemcached service:name=memcachedstate=restarted ../memcached/tasks: main.yml -name:installmemcached yum:name=memcachedstate=latest -name:installconffile template:src=memcached.j2dest=/etc/sysconfig/memcached tags:mcconf notify:reloadmemcached -name:startmemcachedservice service:name=memcachedstate=startedenabled=true ../memcached/templates: memcached.j2 PORT="11211" USER="memcached" MAXCONN="1024" CACHESIZE="{{ansible_memtotal_mb//4}}" OPTIONS="" [root@Centos6memcached]# 安装mysql vimmysql/tasks/main.yml mysql/tasks: main.yml -name:installmysql-server yum:name=mysql-serverstate=latest when:ansible_distribution=="Centos"andansible_distribution_major_version=="6" -name:installmariadb-server yum:name=mariadb-serverstate=latest when:ansible_distribution=="Centos"andansible_distribution_major_version=="7" -name:startmysqlservice service:name=mysqldstate=started when:ansible_distribution=="Centos"andansible_distribution_major_version=="6" -name:startmariadbservice service:name=mariadbstate=started when:ansible_distribution=="Centos"andansible_distribution_major_version=="7" [root@Centos6ansible]#vimmysql.yml -hosts:webserver remote_user:root roles: -mysql 语法测试: ansible-playbook--syntax-checkmysql.yml done!!! 以上配置环境皆基于CentOS 7.2来实现并完成,如有错误请指出,我们共同学习......

优秀的个人博客,低调大师

Appium+python自动化8-Appium Python API

前言: Appium Python API全集,不知道哪个大神整理的,这里贴出来分享给大家。 1.contexts contexts(self): Returns the contexts within the current session. 返回当前会话中的上下文,使用后可以识别H5页面的控件 :Usage: driver.contexts 用法 driver.contexts 2. current_context current_context(self): Returns the current context of the current session. 返回当前会话的当前上下文 :Usage: driver.current_context 用法driver. current_context 3. context context(self): Returns the current context of the current session. 返回当前会话的当前上下文。 :Usage: driver.context 用法driver. Context 4. find_element_by_ios_uiautomation find_element_by_ios_uiautomation(self, uia_string): Finds an element by uiautomation in iOS. 通过iOS uiautomation查找元素 :Args: - uia_string - The element name in the iOS UIAutomation library :Usage: driver.find_element_by_ios_uiautomation('.elements()[1].cells()[2]') 用法dr. find_element_by_ios_uiautomation(‘elements’) 5. find_element_by_accessibility_id find_element_by_accessibility_id(self, id): Finds an element by accessibility id. 通过accessibility id查找元素 :Args: - id - a string corresponding to a recursive element search using the Id/Name that the native Accessibility options utilize :Usage: driver.find_element_by_accessibility_id() 用法driver.find_element_by_accessibility_id(‘id’) 6.scroll scroll(self, origin_el, destination_el): Scrolls from one element to another 从元素origin_el滚动至元素destination_el :Args: - originalEl - the element from which to being scrolling - destinationEl - the element to scroll to :Usage: driver.scroll(el1, el2) 用法 driver.scroll(el1,el2) 7. drag_and_drop drag_and_drop(self, origin_el, destination_el): Drag the origin element to the destination element 将元素origin_el拖到目标元素destination_el :Args: - originEl - the element to drag - destinationEl - the element to drag to 用法 driver.drag_and_drop(el1,el2) 8.tap tap(self, positions, duration=None): Taps on an particular place with up to five fingers, holding for a certain time 模拟手指点击(最多五个手指),可设置按住时间长度(毫秒) :Args: - positions - an array of tuples representing the x/y coordinates of the fingers to tap. Length can be up to five. - duration - (optional) length of time to tap, in ms :Usage: driver.tap([(100, 20), (100, 60), (100, 100)], 500) 用法 driver.tap([(x,y),(x1,y1)],500) 9. swipe swipe(self, start_x, start_y, end_x, end_y, duration=None): Swipe from one point to another point, for an optional duration. 从A点滑动至B点,滑动时间为毫秒 :Args: - start_x - x-coordinate at which to start - start_y - y-coordinate at which to start - end_x - x-coordinate at which to stop - end_y - y-coordinate at which to stop - duration - (optional) time to take the swipe, in ms. :Usage: driver.swipe(100, 100, 100, 400) 用法 driver.swipe(x1,y1,x2,y2,500) 10.flick flick(self, start_x, start_y, end_x, end_y): Flick from one point to another point. 按住A点后快速滑动至B点 :Args: - start_x - x-coordinate at which to start - start_y - y-coordinate at which to start - end_x - x-coordinate at which to stop - end_y - y-coordinate at which to stop :Usage: driver.flick(100, 100, 100, 400) 用法 driver.flick(x1,y1,x2,y2) 11.pinch pinch(self, element=None, percent=200, steps=50): Pinch on an element a certain amount 在元素上执行模拟双指捏(缩小操作) :Args: - element - the element to pinch - percent - (optional) amount to pinch. Defaults to 200% - steps - (optional) number of steps in the pinch action :Usage: driver.pinch(element) 用法 driver.pinch(element) 12.zoom zoom(self, element=None, percent=200, steps=50): Zooms in on an element a certain amount 在元素上执行放大操作 :Args: - element - the element to zoom - percent - (optional) amount to zoom. Defaults to 200% - steps - (optional) number of steps in the zoom action :Usage: driver.zoom(element) 用法 driver.zoom(element) 13.reset reset(self): Resets the current application on the device. 重置应用(类似删除应用数据) 用法 driver.reset() 14. hide_keyboard hide_keyboard(self, key_name=None, key=None, strategy=None): Hides the software keyboard on the device. In iOS, use `key_name` to press a particular key, or `strategy`. In Android, no parameters are used. 隐藏键盘,iOS使用key_name隐藏,安卓不使用参数 :Args: - key_name - key to press - strategy - strategy for closing the keyboard (e.g., `tapOutside`) driver.hide_keyboard() 15. keyevent keyevent(self, keycode, metastate=None): Sends a keycode to the device. Android only. Possible keycodes can be found in http://developer.android.com/reference/android/view/KeyEvent.html. 发送按键码(安卓仅有),按键码可以上网址中找到 :Args: - keycode - the keycode to be sent to the device - metastate - meta information about the keycode being sent 用法 dr.keyevent(‘4’) 16. press_keycode press_keycode(self, keycode, metastate=None): Sends a keycode to the device. Android only. Possible keycodes can be found in http://developer.android.com/reference/android/view/KeyEvent.html. 发送按键码(安卓仅有),按键码可以上网址中找到 :Args: - keycode - the keycode to be sent to the device - metastate - meta information about the keycode being sent 用法 driver.press_ keycode(‘4’) dr.keyevent(‘4’)与driver.press_ keycode(‘4’) 功能实现上一样的,都是按了返回键 17. long_press_keycode long_press_keycode(self, keycode, metastate=None): Sends a long press of keycode to the device. Android only. Possible keycodes can be found in http://developer.android.com/reference/android/view/KeyEvent.html. 发送一个长按的按键码(长按某键) :Args: - keycode - the keycode to be sent to the device - metastate - meta information about the keycode being sent 用法 driver.long_press_keycode(‘4’) 18.current_activity current_activity(self): Retrieves the current activity on the device. 获取当前的activity 用法 print(driver.current_activity()) 19. wait_activity wait_activity(self, activity, timeout, interval=1): Wait for an activity: block until target activity presents or time out. This is an Android-only method. 等待指定的activity出现直到超时,interval为扫描间隔1秒 即每隔几秒获取一次当前的activity 返回的True 或 False :Agrs: - activity - target activity - timeout - max wait time, in seconds - interval - sleep interval between retries, in seconds 用法driver.wait_activity(‘.activity.xxx’,5,2) 20. background_app background_app(self, seconds): Puts the application in the background on the device for a certain duration. 后台运行app多少秒 :Args: - seconds - the duration for the application to remain in the background 用法 driver.background_app(5) 置后台5秒后再运行 21.is_app_installed is_app_installed(self, bundle_id): Checks whether the application specified by `bundle_id` is installed on the device. 检查app是否有安装 返回 True or False :Args: - bundle_id - the id of the application to query 用法 driver.is_app_installed(“com.xxxx”) 22.install_app install_app(self, app_path): Install the application found at `app_path` on the device. 安装app,app_path为安装包路径 :Args: - app_path - the local or remote path to the application to install 用法 driver.install_app(app_path) 23.remove_app remove_app(self, app_id): Remove the specified application from the device. 删除app :Args: - app_id - the application id to be removed 用法 driver.remove_app(“com.xxx.”) 24.launch_app launch_app(self): Start on the device the application specified in the desired capabilities. 启动app 用法 driver.launch_app() 25.close_app close_app(self): Stop the running application, specified in the desired capabilities, on the device. 关闭app 用法 driver.close_app() 启动和关闭app运行好像会出错 26. start_activity start_activity(self, app_package, app_activity, **opts): Opens an arbitrary activity during a test. If the activity belongs to another application, that application is started and the activity is opened. This is an Android-only method. 在测试过程中打开任意活动。如果活动属于另一个应用程序,该应用程序的启动和活动被打开。 这是一个安卓的方法 :Args: - app_package - The package containing the activity to start. - app_activity - The activity to start. - app_wait_package - Begin automation after this package starts (optional). - app_wait_activity - Begin automation after this activity starts (optional). - intent_action - Intent to start (optional). - intent_category - Intent category to start (optional). - intent_flags - Flags to send to the intent (optional). - optional_intent_arguments - Optional arguments to the intent (optional). - stop_app_on_reset - Should the app be stopped on reset (optional)? 用法 driver.start_activity(app_package, app_activity) 27.lock lock(self, seconds): Lock the device for a certain period of time. iOS only. 锁屏一段时间 iOS专有 :Args: - the duration to lock the device, in seconds 用法 driver.lock() 28.shake shake(self): Shake the device. 摇一摇手机 用法 driver.shake() 29.open_notifications open_notifications(self): Open notification shade in Android (API Level 18 and above) 打系统通知栏(仅支持API 18 以上的安卓系统) 用法 driver.open_notifications() 30.network_connection network_connection(self): Returns an integer bitmask specifying the network connection type. Android only. 返回网络类型 数值 Possible values are available through the enumeration `appium.webdriver.ConnectionType` 用法 driver.network_connection 31. set_network_connection set_network_connection(self, connectionType): Sets the network connection type. Android only. Possible values: Value (Alias) | Data | Wifi | Airplane Mode ------------------------------------------------- 0 (None) | 0 | 0 | 0 1 (Airplane Mode) | 0 | 0 | 1 2 (Wifi only) | 0 | 1 | 0 4 (Data only) | 1 | 0 | 0 6 (All network on) | 1 | 1 | 0 These are available through the enumeration appium.webdriver.ConnectionType` 设置网络类型 :Args: - connectionType - a member of the enum appium.webdriver.ConnectionType 用法 先加载from appium.webdriver.connectiontype import ConnectionType dr.set_network_connection(ConnectionType.WIFI_ONLY) ConnectionType的类型有 NO_CONNECTION = 0 AIRPLANE_MODE = 1 WIFI_ONLY = 2 DATA_ONLY = 4 ALL_NETWORK_ON = 6 32. available_ime_engines available_ime_engines(self): Get the available input methods for an Android device. Package and activity are returned (e.g., ['com.android.inputmethod.latin/.LatinIME']) Android only. 返回安卓设备可用的输入法 用法print(driver.available_ime_engines) 33.is_ime_active is_ime_active(self): Checks whether the device has IME service active. Returns True/False. Android only. 检查设备是否有输入法服务活动。返回真/假。 安卓 用法 print(driver.is_ime_active()) 34.activate_ime_engine activate_ime_engine(self, engine): Activates the given IME engine on the device. Android only. 激活安卓设备中的指定输入法,设备可用输入法可以从“available_ime_engines”获取 :Args: - engine - the package and activity of the IME engine to activate (e.g., 'com.android.inputmethod.latin/.LatinIME') 用法 driver.activate_ime_engine(“com.android.inputmethod.latin/.LatinIME”) 35.deactivate_ime_engine deactivate_ime_engine(self): Deactivates the currently active IME engine on the device. Android only. 关闭安卓设备当前的输入法 用法 driver.deactivate_ime_engine() 36.active_ime_engine active_ime_engine(self): Returns the activity and package of the currently active IME engine (e.g., 'com.android.inputmethod.latin/.LatinIME'). Android only. 返回当前输入法的包名 用法 driver.active_ime_engine 37. toggle_location_services toggle_location_services(self): Toggle the location services on the device. Android only. 打开安卓设备上的位置定位设置 用法 driver.toggle_location_services() 38.set_location set_location(self, latitude, longitude, altitude): Set the location of the device 设置设备的经纬度 :Args: - latitude纬度 - String or numeric value between -90.0 and 90.00 - longitude经度 - String or numeric value between -180.0 and 180.0 - altitude海拔高度- String or numeric value 用法 driver.set_location(纬度,经度,高度) 39.tag_name tag_name(self): This element's ``tagName`` property. 返回元素的tagName属性 经实践返回的是class name 用法 element.tag_name() 40.text text(self): The text of the element. 返回元素的文本值 用法 element.text() 41.click click(self): Clicks the element. 点击元素 用法 element.click() 42.submit submit(self): Submits a form. 提交表单 用法 暂无 43.clear clear(self): Clears the text if it's a text entry element. 清除输入的内容 用法 element.clear() 44.get_attribute get_attribute(self, name): 详见@chenhengjie123的超级链接 Gets the given attribute or property of the element. 1、获取 content-desc 的方法为 get_attribute("name") ,而且还不能保证返回的一定是 content-desc (content-desc 为空时会返回 text 属性值) 2、get_attribute 方法不是我们在 uiautomatorviewer 看到的所有属性都能获取的(此处的名称均为使用 get_attribute 时使用的属性名称): 可获取的: 字符串类型: name(返回 content-desc 或 text) text(返回 text) className(返回 class,只有 API=>18 才能支持) resourceId(返回 resource-id,只有 API=>18 才能支持) This method will first try to return the value of a property with the given name. If a property with that name doesn't exist, it returns the value of the attribute with the same name. If there's no attribute with that name, ``None`` is returned. Values which are considered truthy, that is equals "true" or "false", are returned as booleans. All other non-``None`` values are returned as strings. For attributes or properties which do not exist, ``None`` is returned. :Args: - name - Name of the attribute/property to retrieve. Example:: # Check if the "active" CSS class is applied to an element. is_active = "active" in target_element.get_attribute("class") 用法 暂无 45.is_selected is_selected(self): Returns whether the element is selected. Can be used to check if a checkbox or radio button is selected. 返回元素是否选择。 可以用来检查一个复选框或单选按钮被选中。 用法 element.is_slected() 46.is_enabled is_enabled(self): Returns whether the element is enabled. 返回元素是否可用True of False 用法 element.is_enabled() 47.find_element_by_id find_element_by_id(self, id_): Finds element within this element's children by ID. 通过元素的ID定位元素 :Args: - id_ - ID of child element to locate. 用法 driver. find_element_by_id(“id”) 48. find_elements_by_id find_elements_by_id(self, id_): Finds a list of elements within this element's children by ID. 通过元素ID定位,含有该属性的所有元素 :Args: - id_ - Id of child element to find. 用法 driver. find_elements_by_id(“id”) 49. find_element_by_name find_element_by_name(self, name): Finds element within this element's children by name. 通过元素Name定位(元素的名称属性text) :Args: - name - name property of the element to find. 用法 driver.find_element_by_name(“name”) 50. find_elements_by_name find_elements_by_name(self, name): Finds a list of elements within this element's children by name. 通过元素Name定位(元素的名称属性text),含有该属性的所有元素 :Args: - name - name property to search for. 用法 driver.find_element_by_name(“name”) 51. find_element_by_link_text find_element_by_link_text(self, link_text): Finds element within this element's children by visible link text. 通过元素可见链接文本定位 :Args: - link_text - Link text string to search for. 用法 driver.find_element_by_link_text(“text”) 52. find_elements_by_link_text find_element_by_link_text(self, link_text): Finds a list of elements within this element's children by visible link text 通过元素可见链接文本定位,含有该属性的所有元素 :Args: - link_text - Link text string to search for. 用法 driver.find_elements_by_link_text(“text”) 53. find_element_by_partial_link_text find_element_by_partial_link_text(self, link_text): Finds element within this element's children by partially visible link text. 通过元素部分可见链接文本定位 :Args: - link_text - Link text string to search for. driver. find_element_by_partial_link_text(“text”) 54. find_elements_by_partial_link_text find_elements_by_partial_link_text(self, link_text): Finds a list of elements within this element's children by link text. 通过元素部分可见链接文本定位,含有该属性的所有元素 :Args: - link_text - Link text string to search for. driver. find_elements_by_partial_link_text(“text”) 55. find_element_by_tag_name find_element_by_tag_name(self, name): Finds element within this element's children by tag name. 通过查找html的标签名称定位元素 :Args: - name - name of html tag (eg: h1, a, span) 用法 driver.find_element_by_tag_name(“name”) 56. find_elements_by_tag_name find_elements_by_tag_name(self, name): Finds a list of elements within this element's children by tag name. 通过查找html的标签名称定位所有元素 :Args: - name - name of html tag (eg: h1, a, span) 用法driver.find_elements_by_tag_name(“name”) 57. find_element_by_xpath find_element_by_xpath(self, xpath): Finds element by xpath. 通过Xpath定位元素,详细方法可参阅http://www.w3school.com.cn/xpath/ :Args: xpath - xpath of element to locate. "//input[@class='myelement']" Note: The base path will be relative to this element's location. This will select the first link under this element. :: myelement.find_elements_by_xpath(".//a") However, this will select the first link on the page. :: myelement.find_elements_by_xpath("//a") 用法 find_element_by_xpath(“//*”) 58. find_elements_by_xpath find_elements_by_xpath(self, xpath): Finds elements within the element by xpath. :Args: - xpath - xpath locator string. Note: The base path will be relative to this element's location. This will select all links under this element. :: myelement.find_elements_by_xpath(".//a") However, this will select all links in the page itself. :: myelement.find_elements_by_xpath("//a") 用法find_elements_by_xpath(“//*”) 59. find_element_by_class_name find_element_by_class_name(self, name): Finds element within this element's children by class name. 通过元素class name属性定位元素 :Args: - name - class name to search for. 用法 driver. find_element_by_class_name(“android.widget.LinearLayout”) 60. find_elements_by_class_name find_elements_by_class_name(self, name): Finds a list of elements within this element's children by class name. 通过元素class name属性定位所有含有该属性的元素 :Args: - name - class name to search for. 用法 driver. find_elements_by_class_name(“android.widget.LinearLayout”) 61. find_element_by_css_selector find_element_by_css_selector(self, css_selector): Finds element within this element's children by CSS selector. 通过CSS选择器定位元素 :Args: - css_selector - CSS selctor string, ex: 'a.nav#home' 62.send_keys send_keys(self, *value): Simulates typing into the element. 在元素中模拟输入(开启appium自带的输入法并配置了appium输入法后,可以输入中英文) :Args: - value - A string for typing, or setting form fields. For setting file inputs, this could be a local file path. Use this to send simple key events or to fill out form fields:: form_textfield = driver.find_element_by_name('username') form_textfield.send_keys("admin") This can also be used to set file inputs. :: file_input = driver.find_element_by_name('profilePic') file_input.send_keys("path/to/profilepic.gif") # Generally it's better to wrap the file path in one of the methods # in os.path to return the actual path to support cross OS testing. # file_input.send_keys(os.path.abspath("path/to/profilepic.gif")) driver.element.send_keys(“中英”) 63. is_displayed is_displayed(self): Whether the element is visible to a user. 此元素用户是否可见。简单地说就是隐藏元素和被控件挡住无法操作的元素(仅限 Selenium,appium是否实现了类似功能不是太确定)这一项都会返回 False 用法 driver.element.is_displayed() 64. location_once_scrolled_into_view location_once_scrolled_into_view(self): """THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover where on the screen an element is so that we can click it. This method should cause the element to be scrolled into view. Returns the top lefthand corner location on the screen, or ``None`` if the element is not visible. 暂不知道用法 """ 65.size size(self): The size of the element. 获取元素的大小(高和宽) new_size["height"] = size["height"] new_size["width"] = size["width"] 用法 driver.element.size 66. value_of_css_property value_of_css_property(self, property_name): The value of a CSS property. CSS属性 用法 暂不知 67.location location(self): The location of the element in the renderable canvas. 获取元素左上角的坐标 用法 driver.element.location '''返回element的x坐标, int类型''' driver.element.location.get('x') '''返回element的y坐标, int类型''' driver.element.location.get('y') 68.rect rect(self): A dictionary with the size and location of the element. 元素的大小和位置的字典 69. screenshot_as_base64 screenshot_as_base64(self): Gets the screenshot of the current element as a base64 encoded string. 获取当前元素的截图为Base64编码的字符串 :Usage: img_b64 = element.screenshot_as_base64 70.execute_script execute_script(self, script, *args): Synchronously Executes JavaScript in the current window/frame. 在当前窗口/框架(特指 Html 的 iframe )同步执行 javascript 代码。你可以理解为如果这段代码是睡眠5秒,这五秒内主线程的 javascript 不会执行 :Args: - script: The JavaScript to execute. - \*args: Any applicable arguments for your JavaScript. :Usage: driver.execute_script('document.title') 71.execute_async_script execute_async_script(self, script, *args): Asynchronously Executes JavaScript in the current window/frame. 插入 javascript 代码,只是这个是异步的,也就是如果你的代码是睡眠5秒,那么你只是自己在睡,页面的其他 javascript 代码还是照常执行 :Args: - script: The JavaScript to execute. - \*args: Any applicable arguments for your JavaScript. :Usage: driver.execute_async_script('document.title') 72.current_url current_url(self): Gets the URL of the current page. 获取当前页面的网址。 :Usage: driver.current_url 用法 driver.current_url 73. page_source page_source(self): Gets the source of the current page. 获取当前页面的源。 :Usage: driver.page_source 74.close close(self): Closes the current window. 关闭当前窗口 :Usage: driver.close() 75.quit quit(self): Quits the driver and closes every associated window. 退出脚本运行并关闭每个相关的窗口连接 :Usage: driver.quit() 在学习过程中有遇到疑问的,可以加appium(python+java) QQ群交流:512200893 word版的,在群附件也可以下载到

优秀的个人博客,低调大师

Appium+python自动化3-启动淘宝app

前言 前面两篇环境已经搭建好了,接下来就是需要启动APP,如何启动app呢?首先要获取包名,然后获取launcherActivity。获取这两个关键东西的方法很多,这里就不一一多说,小伙伴们可以各显神通。小编这里主要给大家推荐一个sdk自带的实用工具aapt. aapt即Android Asset Packaging Tool,在SDK的build-tools目录下。该工具可以查看apk包名和launcherActivity,当然还有更多的功能,有兴趣的可以查看相关资料。 一、下载aapt 1.在android-sdk里面双击SDK-manager,下载buidl-tools 2.勾选build-tools,随便选一个版本,我这里选的是24的版本 3.下载完成后,在D:\androidsdk\android-sdk-windows\build-tools\24.0.0目录下找到aapt.exe,将这个路径设置环境变量,添加到path下 4.打开cmd。输入aapt出现如下界面,说明环境OK了 二、获取apk包名 1.将准备测试的APK放到D盘某个目录,如D:\test 2.打开cmd,输入指令aapt dump badging D:\test\xxx.apk(APK的全名,如手机淘宝.apk) 3.以手机淘宝.apk为例,如下图 4.这里就可以看到apk的包名:com.taobao.taobao 注:老司机可以直接把apk放在桌面上,输入指令后拖到cmd框 三、获取launcherActivity 1.接着上一步操作,cmd屏幕拖到中间l找到auncherActivity 2.这里可以看到,淘宝的launcherActivity值为com.taobao.tao.welcome.Welcome 四、写脚本 1platformName:这里是android的apk 2.deviceName:手机设备名称,通过adb devices查看 3.platformVersion:android系统的版本号 4.appPackage:apk包名 5.appActivity:apk的launcherActivity 五、运行appium 1.启动appium,右上角点三角形按钮,变成正方形,就是启动状态。 2.确认手机连上电脑 3.在pycharm运行脚本,随后在手机上会弹出安装下面两个软件的提示,安装后,桌面上多两个图标。那么恭喜你启动成功! 4.接着会看到淘宝app已经启动啦,有木有小激动~~ 六、最终代码如下 # coding=utf-8 from appium import webdriver desired_caps = { 'platformName': 'Android', 'deviceName': '30d4e606', 'platformVersion': '5.0', # apk包名 'appPackage': 'com.taobao.taobao', # apk的launcherActivity 'appActivity': 'com.taobao.tao.welcome.Welcome' } driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) 这个地址是怎么来的呢? 这一篇主要学会使用aapt工具,然后启动app的一个流程,启动app后,下一步就是要定位元素了,定位元素android sdk里面用一个自带的uiautomatorviewer,appium里面也有一个Inspector,下篇会详细介绍。 在学习过程中有遇到疑问的,可以加appium(python+java) QQ群交流:512200893

优秀的个人博客,低调大师

Appium+python自动化4-元素定位uiautomatorviewer

前言 环境搭建好了,下一步元素定位,元素定位本篇主要介绍如何使用uiautomatorviewer,通过定位到页面上的元素,然后进行相应的点击等操作. uiautomatorviewer是android-sdk自带的一个元素定位工具,非常简单好用,使用uiautomatorviewer,你可以检查一个应用的UI来查看应用的布局和组件以及相关的属性。 一、启动uiautomatorviewer.bat 1.打开目录D:\androidsdk\android-sdk-windows\tools 1472105236126324.png850x502 53 KB 2.双击启动,启动之后出现如下界面 3如果不喜欢双击启动的话,也可以在cmd里面通过指令启动 先cd到tools目录下,然后输入uiautomatorviewer.bat回车后启动服务 二、连接手机 1.cmd打开输入adb devices,确认手机已连上 2.打开手机淘宝页面,让屏幕处于点亮状态 3.点左上角安卓机器人按钮Devices Screenshot按钮刷新页面 三、定位元素 1.移动鼠标到需要定位的元素上,如搜索输入框 2.右下角可以看到元素对应的属性 text:搭配新宠不能缺 resource-id:com.taobao.taobao:id/home_searchedit class:android.widget.EditText 四、点搜索框 1.前面一骗启动app后,休眠五秒,等待页面加载完成 2.通过id来定位到搜索框,然后点击 五、最终代码如下 # coding=utf-8 from appium import webdriver import time desired_caps = { 'platformName': 'Android', 'deviceName': '30d4e606', 'platformVersion': '5.0', 'appPackage': 'com.taobao.taobao', 'appActivity': 'com.taobao.tao.welcome.Welcome', } driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) # 休眠五秒等待页面加载完成 time.sleep(5) driver.find_element_by_id("com.taobao.taobao:id/home_searchedit").click() 六、元素定位 (此处敲黑板,做笔记!!!) 1.appium的webdriver提供了11种元素定位方法,在selenium的基础上扩展了三个,可以在pycharm里面输入driver.find_element_by然后会自动匹配出来 2.多的三种如下,在后面的会详细介绍 driver.find_element_by_accessibility_id() driver.find_element_by_android_uiautomator() driver.find_element_by_ios_uiautomation() (第三个是ios的可以暂时不用管) uiautomatorviewer是android sdk自带的,下篇介绍appium自带个元素定位工具:Inspector.在 在学习过程中有遇到疑问的,可以加appium(python+java) QQ群交流:512200893

资源下载

更多资源
Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册