站内公告:

我们的虚拟社区正式开通了

Main Menu

最新帖子

#51
VMware / vmrun命令行的使用(VMWare虚拟机)
上次发布者 jvip_chen - 2022-5月-25 10:37 上午
VMware Workstation 虚拟机中 vmrun 命令的使用

基本命令:
vmrun -T ws start "/opt/VMware/win2k8r2.vmx" nogui
# 启动无图形界面虚拟机 
#(-T 是区分宿主机的类型,ws|server|server1|fusion|esx|vc|player,比较常用的是ws、esx和player)
vmrun start "/opt/VMware/win2k8r2.vmx" gui
# 启动带图形界面虚拟机
vmrun stop "/opt/VMware/win2k8r2.vmx" hard | soft
# 强制关闭虚拟机(相当于直接关电源) | 正常关闭虚拟机
vmrun reset "/opt/VMware/win2k8r2.vmx" hard | soft
# 冷重启虚拟机 | 热重启虚拟机
vmrun suspend  "/opt/VMware/win2k8r2.vmx" hard | soft
# 挂起虚拟机(可能相当于休眠)
vmrun pause  "/opt/VMware/win2k8r2.vmx"
# 暂停虚拟机
vmrun unpause  "/opt/VMware/win2k8r2.vmx"
# 停止暂停虚拟机   
vmrun list
# 列出正在运行的虚拟机
ps aux | grep vmx
# 另一种查看正在运行虚拟机的方法
vmrun -T ws snapshot "/opt/VMware/win2k8r2.vmx" snapshotName
# 创建一个快照(snapshotName 快照名)
vmrun -T ws reverToSnapshot "/opt/VMware/win2k8r2.vmx" snapshotName
# 从一个快照中恢复虚拟机(snapshotName 快照名)
vmrun -T ws listSnapshots "/opt/VMware/win2k8r2.vmx"
# 列出虚拟机快照数量及名称
vmrun -T ws deleteSnapshot "/opt/VMware/win2k8r2.vmx" snapshotName
# 删除一个快照(snapshotName 快照名)
#52
VMware / vmware命令行
上次发布者 jvip_chen - 2022-5月-25 10:35 上午
本篇讲解几个简单的vmware的命令。
vmrun start "d:\\centos\\qs.vmx" nogui 无界面启动
vmrun start "d:\\centos\\qs.vmx" gui 图形化界面启动
vmrun list 列出正在运行的虚拟机
vmrun stop "d:\\centos\\qs.vmx" soft 正常关闭虚拟机
vmrun stop "d:\\centos\\qs.vmx" hard 强制关闭虚拟机
vmrun reset "d:\\centos\\qs.vmx" soft 热重启虚拟机
vmrun reset "d:\\centos\\qs.vmx" hard 冷重启虚拟机
vmrun sudpend "d:\\centos\\qs.vmx" soft 热挂起(休眠)
vmrun sudpend "d:\\centos\\qs.vmx" hard 冷挂起(休眠)
vmrun pause "d:\\centos\\qs.vmx" 暂停虚拟机
vmrun listsnapshots "d:\\centos\\qs.vmx" 查看某虚拟机有多少快照
vmrun snapshot "d:\\centos\\qs.vmx" snapshotcmdtest 创建快照
vmrun deleteSnapshot "d:\\centos\\qs.vmx" snapshotcmdtest 删除一个快照
vmrun revertToSnapshot "d:\\centos\\qs.vmx" snapshotcmdtest 从快照中恢复
Invalid argument: --help
vmrun version 1.15.0 build-2985596

Usage: vmrun [AUTHENTICATION-FLAGS] COMMAND [PARAMETERS]



AUTHENTICATION-FLAGS
--------------------
These must appear before the command and any command parameters.

-h <hostName> (not needed for Workstation)
-P <hostPort> (not needed for Workstation)
-T <hostType> (ws|server|server1|fusion|esx|vc|player)
for example, use '-T server' for Server 2.0
use '-T server1' for Server 1.0
use '-T ws' for VMware Workstation
use '-T ws-shared' for VMware Workstation (shared mode)
use '-T esx' for VMware ESX
use '-T vc' for VMware vCenter Server
-u <userName in host OS> (not needed for Workstation)
-p <password in host OS> (not needed for Workstation)
-vp <password for encrypted virtual machine>
-gu <userName in guest OS>
-gp <password in guest OS>

// 关于虚拟机电源的命令

POWER COMMANDS PARAMETERS DESCRIPTION
-------------- ---------- -----------
start Path to vmx file Start a VM or Team (vmrun start "d:\\centos\\qs.vmx" nogui 无界面启动)
[gui|nogui] (vmrun start "d:\\centos\\qs.vmx" gui 图形化界面启动)

stop Path to vmx file Stop a VM or Team (vmrun stop "d:\\centos\\qs.vmx" soft 正常关闭虚拟机)
[hard|soft] (vmrun stop "d:\\centos\\qs.vmx" hard 强制关闭虚拟机)

reset Path to vmx file Reset a VM or Team (vmrun reset "d:\\centos\\qs.vmx" soft 热重启虚拟机)
[hard|soft] (vmrun reset "d:\\centos\\qs.vmx" hard 冷重启虚拟机)

suspend Path to vmx file Suspend a VM or Team (vmrun sudpend "d:\\centos\\qs.vmx" soft 热挂起)
[hard|soft] (vmrun sudpend "d:\\centos\\qs.vmx" hard 冷挂起)

pause Path to vmx file Pause a VM (vmrun pause "d:\\centos\\qs.vmx" 暂停虚拟机)

unpause Path to vmx file Unpause a VM (vmrun unpause "d:\\centos\\qs.vmx" 从暂停中恢复虚拟机)

// 关于快照的命令

SNAPSHOT COMMANDS PARAMETERS DESCRIPTION
----------------- ---------- -----------
listSnapshots Path to vmx file List all snapshots in a VM
[showTree] (vmrun listSnapshots "d:\\centos\\qs.vmx" 查看某虚拟机有多少快照)

snapshot Path to vmx file Create a snapshot of a VM
Snapshot name (vmrun snapshot "d:\\centos\\qs.vmx" snapshotcmdtest 创建一个快照)

deleteSnapshot Path to vmx file Remove a snapshot from a VM
Snapshot name (vmrun deleteSnapshot "d:\\centos\\qs.vmx" snapshotcmdtest 删除一个快照)
[andDeleteChildren]

revertToSnapshot Path to vmx file Set VM state to a snapshot
Snapshot name (vmrun revertToSnapshot "d:\\centos\\qs.vmx" snapshotcmdtest 从快照中恢复)



GUEST OS COMMANDS PARAMETERS DESCRIPTION
----------------- ---------- -----------
runProgramInGuest Path to vmx file Run a program in Guest OS
[-noWait]
[-activeWindow]
[-interactive]
Complete-Path-To-Program
[Program arguments]

fileExistsInGuest Path to vmx file Check if a file exists in Guest OS
Path to file in guest

directoryExistsInGuest Path to vmx file Check if a directory exists in Guest OS
Path to directory in guest

setSharedFolderState Path to vmx file Modify a Host-Guest shared folder
Share name
Host path
writable | readonly

addSharedFolder Path to vmx file Add a Host-Guest shared folder
Share name
New host path

removeSharedFolder Path to vmx file Remove a Host-Guest shared folder
Share name

enableSharedFolders Path to vmx file Enable shared folders in Guest
[runtime]

disableSharedFolders Path to vmx file Disable shared folders in Guest
[runtime]

listProcessesInGuest Path to vmx file List running processes in Guest OS

killProcessInGuest Path to vmx file Kill a process in Guest OS
process id

runScriptInGuest Path to vmx file Run a script in Guest OS
[-noWait]
[-activeWindow]
[-interactive]
Interpreter path
Script text

deleteFileInGuest Path to vmx file Delete a file in Guest OS
Path in guest

createDirectoryInGuest Path to vmx file Create a directory in Guest OS
Directory path in guest

deleteDirectoryInGuest Path to vmx file Delete a directory in Guest OS
Directory path in guest

CreateTempfileInGuest Path to vmx file Create a temporary file in Guest OS

listDirectoryInGuest Path to vmx file List a directory in Guest OS
Directory path in guest

CopyFileFromHostToGuest Path to vmx file Copy a file from host OS to guest OS
Path on host Path in guest


CopyFileFromGuestToHost Path to vmx file Copy a file from guest OS to host OS
Path in guest Path on host


renameFileInGuest Path to vmx file Rename a file in Guest OS
Original name
New name

captureScreen Path to vmx file Capture the screen of the VM to a local file
Path on host

writeVariable Path to vmx file Write a variable in the VM state
[runtimeConfig|guestEnv|guestVar]
variable name
variable value

readVariable Path to vmx file Read a variable in the VM state
[runtimeConfig|guestEnv|guestVar]
variable name

getGuestIPAddress Path to vmx file Gets the IP address of the guest
[-wait]



GENERAL COMMANDS PARAMETERS DESCRIPTION
---------------- ---------- -----------
list List all running VMs (vmrun list 列出所有正在运行的虚拟机)

upgradevm Path to vmx file Upgrade VM file format, virtual hw

installTools Path to vmx file Install Tools in Guest

checkToolsState Path to vmx file Check the current Tools state

register Path to vmx file Register a VM

unregister Path to vmx file Unregister a VM

listRegisteredVM List registered VMs

deleteVM Path to vmx file Delete a VM (vmrun deleteVM vmname 删除名为vmname的虚拟机)

clone Path to vmx file Create a copy of the VM (克隆一个虚拟机:完全克隆/链接克隆)
Path to destination vmx file
full|linked
[-snapshot=Snapshot Name]
[-cloneName=Name]




Examples:


Starting a virtual machine with Workstation on a Windows host
   vmrun -T ws start "c:\my VMs\myVM.vmx"
Stopping a virtual machine on an ESX host
   vmrun -T esx -h https://myHost.com/sdk -u hostUser -p hostPassword stop "[storage1] vm/myVM.vmx"
Running a program in a virtual machine with Workstation on a Windows host with Windows guest
   vmrun -T ws -gu guestUser -gp guestPassword runProgramInGuest "c:\my VMs\myVM.vmx" "c:\Program Files\myProgram.exe"Running a program in a virtual machine with Server on a Linux host with Linux guest
vmrun -T server -h https://myHost.com:8333/sdk -u hostUser -p hostPassword -gu guestUser -gp guestPassword runProgramInGuest "[standard] vm/myVM.vmx" /usr/bin/X11/xclock -display :0


Creating a snapshot of a virtual machine with Workstation on a Windows host
   vmrun -T ws snapshot "c:\my VMs\myVM.vmx" mySnapshot
Reverting to a snapshot with Workstation on a Windows host
   vmrun -T ws revertToSnapshot "c:\my VMs\myVM.vmx" mySnapshot
Deleting a snapshot with Workstation on a Windows host
   vmrun -T ws deleteSnapshot "c:\my VMs\myVM.vmx" mySnapshot
Enabling Shared Folders with Workstation on a Windows host
   vmrun -T ws enableSharedFolders "c:\my VMs\myVM.vmx"
#53
VirtualBox / VirtualBox 常用命令汇总
上次发布者 jvip_chen - 2022-5月-25 10:31 上午
VirtualBox 命令汇总

在Linux平台安装的VirtualBox虚拟机,可以通过如下命令操作虚拟机:

查看有哪些虚拟机
VBoxManage list vms
查看虚拟的详细信息
VBoxManage list vms --long
查看运行着的虚拟机
VBoxManage list runningvms
开启虚拟机在后台运行
VBoxManage startvm backup -type headless
开启虚拟机并开启远程桌面连接的支持
VBoxManage startvm <vm_name> -type vrdp
改变虚拟机的远程连接端口,用于多个vbox虚拟机同时运行
VBoxManage controlvm <vm_name> vrdpprot <ports>
关闭虚拟机
VBoxManage controlvm <vm_name> acpipowerbutton
强制关闭虚拟机
VBoxManage controlvm <vm_name> poweroff
杀掉某个虚拟机的进程方法(强制关闭虚拟机)

经常遇到强制关闭虚拟机后,虚拟关不了的现象,状态一直是 stopping,而且一直卡死在这,没办法关闭,所以需要强制关闭这个虚拟机

(1) 查看所有virtualbox进程
ps -aux|grep virtualbox
会查出如下 信息:(蓝色背景文字 为 进程id 和 虚拟机名)

vnc 19499 54.7 3.3 3746624 2177960 ? Sl 15:46 55:49 /usr/lib/virtualbox/VirtualBox --comment SwiftSync2.0_Synctest25 --startvm 7fa1f49b-4dc2-4a7f-865d-5e0456f5482d --no-startvm-errormsgbox

....

然后强制杀进程id为 19499的进程,这个进程就是 虚拟机SwiftSync2.0_Synctest25的进程
kill -9 194999
#54
VirtualBox / Ubuntu下安装VirtualBox
上次发布者 jvip_chen - 2022-5月-25 10:29 上午
之前换了新硬盘,重装了ubuntu,由于学习需要还是要装个虚拟机。以前用过VMWare真的是神卡,这次换VirtualBox,希望开源社区能给我带来曙光:)
添加VirtualBox的源并安装5.1版本
虽然也可以直接安装deb包,但毕竟懒,添加源可以保持更新:
$ sed -i '$adeb http://download.virtualbox.org/virtualbox/debian xenial contrib' /etc/apt/sources.list
为apt-secure导入公钥:
$ wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | sudo apt-key add -
$ wget -q https://www.virtualbox.org/download/oracle_vbox.asc -O- | sudo apt-key add -
通过apt安装VirtualBox和dkms,其中dkms包可以确保在下次通过apt upgrade更新内核时,VirtualBox的内核模块也正确地更新:
$ sudo apt-get update
$ sudo apt-get install virtualbox-5.1 dkms
安装Oracle VM VirtualBox扩展包
这个扩展包据说可以提供USB2.0/3.0、Webcam、远程桌面协议(RDP)、磁盘加密等的支持,对于我这种普通用户来说其实就是USB3.0和RDP的支持比较有用,主要还是本着一颗爱折腾的心。
这个包就不推荐通过apt源来安装了,首先直至目前apt源提供的ext-pack仍然是5.0版本,而最新的virtualBox是5.1版本,不匹配;其次还会遇到一些奇怪的问题导致安装不成功。
首先直接下载这个包:
$ axel -a -n 16 "http://download.virtualbox.org/virtualbox/5.1.6/Oracle_VM_VirtualBox_Extension_Pack-5.1.6-110634.vbox-extpack"然后打开VirtualBox,在管理-全局设定-扩展中选择添加新包。
#55
Linux 系统 / Linux下curl用法详解播
上次发布者 jvip_chen - 2022-5月-25 10:24 上午
Curl(CommandLine Uniform Resource Locator),即在命令行中利用URL进行数据或者文件传输,它是Linux下强大的http命令行工具,其功能十分强大,我们来看下帮助页面,参数非常丰富。

[root@mx ~]# curl -h
Usage: curl [options...] <url>
Options: (H) means HTTP/HTTPS only, (F) means FTP only
     --anyauth       Pick "any" authentication method (H)
 -a, --append        Append to target file when uploading (F/SFTP)
     --basic         Use HTTP Basic Authentication (H)
     --cacert FILE   CA certificate to verify peer against (SSL)
     --capath DIR    CA directory to verify peer against (SSL)
 -E, --cert CERT[:PASSWD] Client certificate file and password (SSL)
     --cert-type TYPE Certificate file type (DER/PEM/ENG) (SSL)
     --ciphers LIST  SSL ciphers to use (SSL)
     --compressed    Request compressed response (using deflate or gzip)
 -K, --config FILE   Specify which config file to read
     --connect-timeout SECONDS  Maximum time allowed for connection
 -C, --continue-at OFFSET  Resumed transfer offset
 -b, --cookie STRING/FILE  String or file to read cookies from (H)
 -c, --cookie-jar FILE  Write cookies to this file after operation (H)
     --create-dirs   Create necessary local directory hierarchy
     --crlf          Convert LF to CRLF in upload
     --crlfile FILE  Get a CRL list in PEM format from the given file
 -d, --data DATA     HTTP POST data (H)
     --data-ascii DATA  HTTP POST ASCII data (H)
     --data-binary DATA  HTTP POST binary data (H)
     --data-urlencode DATA  HTTP POST data url encoded (H)
     --delegation STRING GSS-API delegation permission
     --digest        Use HTTP Digest Authentication (H)
     --disable-eprt  Inhibit using EPRT or LPRT (F)
     --disable-epsv  Inhibit using EPSV (F)
 -D, --dump-header FILE  Write the headers to this file
     --egd-file FILE  EGD socket path for random data (SSL)
     --engine ENGINGE  Crypto engine (SSL). "--engine list" for list
 -f, --fail          Fail silently (no output at all) on HTTP errors (H)
 -F, --form CONTENT  Specify HTTP multipart POST data (H)
     --form-string STRING  Specify HTTP multipart POST data (H)
     --ftp-account DATA  Account data string (F)
     --ftp-alternative-to-user COMMAND  String to replace "USER [name]" (F)
     --ftp-create-dirs  Create the remote dirs if not present (F)
     --ftp-method [MULTICWD/NOCWD/SINGLECWD] Control CWD usage (F)
     --ftp-pasv      Use PASV/EPSV instead of PORT (F)
 -P, --ftp-port ADR  Use PORT with given address instead of PASV (F)
     --ftp-skip-pasv-ip Skip the IP address for PASV (F)
     --ftp-pret      Send PRET before PASV (for drftpd) (F)
     --ftp-ssl-ccc   Send CCC after authenticating (F)
     --ftp-ssl-ccc-mode ACTIVE/PASSIVE  Set CCC mode (F)
     --ftp-ssl-control Require SSL/TLS for ftp login, clear for transfer (F)
 -G, --get           Send the -d data with a HTTP GET (H)
 -g, --globoff       Disable URL sequences and ranges using {} and []
 -H, --header LINE   Custom header to pass to server (H)
 -I, --head          Show document info only
 -h, --help          This help text
     --hostpubmd5 MD5  Hex encoded MD5 string of the host public key. (SSH)
 -0, --http1.0       Use HTTP 1.0 (H)
     --ignore-content-length  Ignore the HTTP Content-Length header
 -i, --include       Include protocol headers in the output (H/F)
 -k, --insecure      Allow connections to SSL sites without certs (H)
     --interface INTERFACE  Specify network interface/address to use
 -4, --ipv4          Resolve name to IPv4 address
 -6, --ipv6          Resolve name to IPv6 address
 -j, --junk-session-cookies Ignore session cookies read from file (H)
     --keepalive-time SECONDS  Interval between keepalive probes
     --key KEY       Private key file name (SSL/SSH)
     --key-type TYPE Private key file type (DER/PEM/ENG) (SSL)
     --krb LEVEL     Enable Kerberos with specified security level (F)
     --libcurl FILE  Dump libcurl equivalent code of this command line
     --limit-rate RATE  Limit transfer speed to this rate
 -l, --list-only     List only names of an FTP directory (F)
     --local-port RANGE  Force use of these local port numbers
 -L, --location      Follow redirects (H)
     --location-trusted like --location and send auth to other hosts (H)
 -M, --manual        Display the full manual
     --mail-from FROM  Mail from this address
     --mail-rcpt TO  Mail to this receiver(s)
     --mail-auth AUTH  Originator address of the original email
     --max-filesize BYTES  Maximum file size to download (H/F)
     --max-redirs NUM  Maximum number of redirects allowed (H)
 -m, --max-time SECONDS  Maximum time allowed for the transfer
     --metalink      Process given URLs as metalink XML file
     --negotiate     Use HTTP Negotiate Authentication (H)
 -n, --netrc         Must read .netrc for user name and password
     --netrc-optional Use either .netrc or URL; overrides -n
     --netrc-file FILE  Set up the netrc filename to use
 -N, --no-buffer     Disable buffering of the output stream
     --no-keepalive  Disable keepalive use on the connection
     --no-sessionid  Disable SSL session-ID reusing (SSL)
     --noproxy       List of hosts which do not use proxy
     --ntlm          Use HTTP NTLM authentication (H)
 -o, --output FILE   Write output to <file> instead of stdout
     --pass PASS     Pass phrase for the private key (SSL/SSH)
     --post301       Do not switch to GET after following a 301 redirect (H)
     --post302       Do not switch to GET after following a 302 redirect (H)
     --post303       Do not switch to GET after following a 303 redirect (H)
 -#, --progress-bar  Display transfer progress as a progress bar
     --proto PROTOCOLS  Enable/disable specified protocols
     --proto-redir PROTOCOLS  Enable/disable specified protocols on redirect
 -x, --proxy [PROTOCOL://]HOST[:PORT] Use proxy on given port
     --proxy-anyauth Pick "any" proxy authentication method (H)
     --proxy-basic   Use Basic authentication on the proxy (H)
     --proxy-digest  Use Digest authentication on the proxy (H)
     --proxy-negotiate Use Negotiate authentication on the proxy (H)
     --proxy-ntlm    Use NTLM authentication on the proxy (H)
 -U, --proxy-user USER[:PASSWORD]  Proxy user and password
     --proxy1.0 HOST[:PORT]  Use HTTP/1.0 proxy on given port
 -p, --proxytunnel   Operate through a HTTP proxy tunnel (using CONNECT)
     --pubkey KEY    Public key file name (SSH)
 -Q, --quote CMD     Send command(s) to server before transfer (F/SFTP)
     --random-file FILE  File for reading random data from (SSL)
 -r, --range RANGE   Retrieve only the bytes within a range
     --raw           Do HTTP "raw", without any transfer decoding (H)
 -e, --referer       Referer URL (H)
 -J, --remote-header-name Use the header-provided filename (H)
 -O, --remote-name   Write output to a file named as the remote file
     --remote-name-all Use the remote file name for all URLs
 -R, --remote-time   Set the remote file's time on the local output
 -X, --request COMMAND  Specify request command to use
     --resolve HOST:PORT:ADDRESS  Force resolve of HOST:PORT to ADDRESS
     --retry NUM   Retry request NUM times if transient problems occur
     --retry-delay SECONDS When retrying, wait this many seconds between each
     --retry-max-time SECONDS  Retry only within this period
 -S, --show-error    Show error. With -s, make curl show errors when they occur
 -s, --silent        Silent mode. Don't output anything
     --socks4 HOST[:PORT]  SOCKS4 proxy on given host + port
     --socks4a HOST[:PORT]  SOCKS4a proxy on given host + port
     --socks5 HOST[:PORT]  SOCKS5 proxy on given host + port
     --socks5-basic  Enable username/password auth for SOCKS5 proxies
     --socks5-gssapi Enable GSS-API auth for SOCKS5 proxies
     --socks5-hostname HOST[:PORT] SOCKS5 proxy, pass host name to proxy
     --socks5-gssapi-service NAME  SOCKS5 proxy service name for gssapi
     --socks5-gssapi-nec  Compatibility with NEC SOCKS5 server
 -Y, --speed-limit RATE  Stop transfers below speed-limit for 'speed-time' secs
 -y, --speed-time SECONDS  Time for trig speed-limit abort. Defaults to 30
     --ssl           Try SSL/TLS (FTP, IMAP, POP3, SMTP)
     --ssl-reqd      Require SSL/TLS (FTP, IMAP, POP3, SMTP)
 -2, --sslv2         Use SSLv2 (SSL)
 -3, --sslv3         Use SSLv3 (SSL)
     --ssl-allow-beast Allow security flaw to improve interop (SSL)
     --stderr FILE   Where to redirect stderr. - means stdout
     --tcp-nodelay   Use the TCP_NODELAY option
 -t, --telnet-option OPT=VAL  Set telnet option
     --tftp-blksize VALUE  Set TFTP BLKSIZE option (must be >512)
 -z, --time-cond TIME  Transfer based on a time condition
 -1, --tlsv1         Use => TLSv1 (SSL)
     --tlsv1.0       Use TLSv1.0 (SSL)
     --tlsv1.1       Use TLSv1.1 (SSL)
     --tlsv1.2       Use TLSv1.2 (SSL)
     --tlsv1.3       Use TLSv1.3 (SSL)
     --tls-max VERSION  Use TLS up to VERSION (SSL)
     --trace FILE    Write a debug trace to the given file
     --trace-ascii FILE  Like --trace but without the hex output
     --trace-time    Add time stamps to trace/verbose output
     --tr-encoding   Request compressed transfer encoding (H)
 -T, --upload-file FILE  Transfer FILE to destination
     --url URL       URL to work with
 -B, --use-ascii     Use ASCII/text transfer
 -u, --user USER[:PASSWORD]  Server user and password
     --tlsuser USER  TLS username
     --tlspassword STRING TLS password
     --tlsauthtype STRING  TLS authentication type (default SRP)
     --unix-socket FILE    Connect through this UNIX domain socket
 -A, --user-agent STRING  User-Agent to send to server (H)
 -v, --verbose       Make the operation more talkative
 -V, --version       Show version number and quit
 -w, --write-out FORMAT  What to output after completion
     --xattr        Store metadata in extended file attributes
 -q                 If used as the first parameter disables .curlrc
[root@mx ~]#
curl在Mac和Linux下是自带的命令行工具,如果你也想在Windows上使用,这里推荐使用"git for windows"这个工具,你可以使用此关键字在网络上检索下载。


安装完成后,点击桌面的"Git Bash"后,就可以在Windows下使用curl命令行工具了。

基本用法
curl是http工具,最简单的使用方法就是直接搭配网址使用,比如请求百度的内容:

[root@mx ~]# curl www.baidu.com

-s 选项:
加上此选项,不显示请求内容的进度信息。

-o 选项:
将获取内容存储到本地文件,-o后接文件名,如把请求的内容存储到1.txt中
# 搭配-s选项一起使用
[root@mx ~]# curl -s https://www.baidu.com -o 1.txt
# 不使用-s时,显示进度信息
[root@mx ~]# curl  https://www.baidu.com -o 2.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2443  100  2443    0     0  14183      0 --:--:-- --:--:-- --:--:-- 14203
[root@mx ~]# cat 1.txt
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head
......
[root@mx ~]#

详细用法
-A 选项:
-A参数指定客户端的用户代理标头,即User-Agent。curl 的默认用户代理字符串是curl/[version]。下面命令将User-Agent改成 Chrome 浏览器。

$ curl -A 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36' https://google.com下面命令会移除User-Agent标头。

$ curl -A '' https://google.com
也可以通过-H参数直接指定标头,更改User-Agent。

$ curl -H 'User-Agent: php/1.0' https://google.com
-b 选项:
-b参数用来向服务器发送 Cookie。

$ curl -b 'foo=bar' https://google.com
上面命令会生成一个标头Cookie: foo=bar,向服务器发送一个名为foo、值为bar的 Cookie。

$ curl -b 'foo1=bar;foo2=bar2' https://google.com
上面命令发送两个 Cookie。

$ curl -b cookies.txt https://www.google.com
上面命令读取本地文件cookies.txt,里面是服务器设置的 Cookie(参见-c参数),将其发送到服务器。

-c 选项:
-c参数将服务器设置的 Cookie 写入一个文件。

$ curl -c cookies.txt https://www.google.com
上面命令将服务器的 HTTP 回应所设置 Cookie 写入文本文件cookies.txt。

-d 选项:
-d参数用于发送 POST 请求的数据体。

$ curl -d'login=emma&password=123'-X POST https://google.com/login
#或者
$ curl -d 'login=emma' -d 'password=123' -X POST  https://google.com/login
使用-d参数以后,HTTP 请求会自动加上标头Content-Type : application/x-www-form-urlencoded。并且会自动将请求转为 POST 方法,因此可以省略-X POST。

-d参数可以读取本地文本文件的数据,向服务器发送。

$ curl -d '@data.txt' https://google.com/login
上面命令读取data.txt文件的内容,作为数据体向服务器发送。

--data-urlencode--data-urlencode参数等同于-d,发送 POST 请求的数据体,区别在于会自动将发送的数据进行 URL 编码。

$ curl --data-urlencode 'comment=hello world' https://google.com/login
上面代码中,发送的数据hello world之间有一个空格,需要进行 URL 编码。

-e 选项:
-e参数用来设置 HTTP 的标头Referer,表示请求的来源。

curl -e 'https://google.com?q=example' https://www.example.com
上面命令将Referer标头设为https://google.com?q=example。

-H参数可以通过直接添加标头Referer,达到同样效果。

引用curl -H 'Referer: https://google.com?q=example' https://www.example.com
-F 参数:
-F参数用来向服务器上传二进制文件。

$ curl -F 'file=@photo.png' https://google.com/profile
上面命令会给 HTTP 请求加上标头Content-Type: multipart/form-data,然后将文件photo.png作为file字段上传。

-F参数可以指定 MIME 类型。

$ curl -F 'file=@photo.png;type=image/png' https://google.com/profile
上面命令指定 MIME 类型为image/png,否则 curl 会把 MIME 类型设为application/octet-stream。

-F参数也可以指定文件名。

$ curl -F 'file=@photo.png;filename=me.png' https://google.com/profile
上面命令中,原始文件名为photo.png,但是服务器接收到的文件名为me.png。

-G 选项:
-G参数用来构造 URL 的查询字符串。

$ curl -G -d 'q=kitties' -d 'count=20' https://google.com/search
上面命令会发出一个 GET 请求,实际请求的 URL 为https://google.com/search?q=kitties&count=20。如果省略--G,会发出一个 POST 请求。

如果数据需要 URL 编码,可以结合--data--urlencode参数。

$ curl -G --data-urlencode 'comment=hello world' https://www.example.com
-H 选项:
-H参数添加 HTTP 请求的标头。

$ curl -H 'Accept-Language: en-US' https://google.com
上面命令添加 HTTP 标头Accept-Language: en-US。

$ curl -H 'Accept-Language: en-US' -H 'Secret-Message: xyzzy' https://google.com
上面命令添加两个 HTTP 标头。

$ curl -d '{"login": "emma", "pass": "123"}' -H 'Content-Type: application/json' https://google.com/login
上面命令添加 HTTP 请求的标头是Content-Type: application/json,然后用-d参数发送 JSON 数据。

-i 选项:
-i参数打印出服务器回应的 HTTP 标头。

$ curl -i https://www.example.com
上面命令收到服务器回应后,先输出服务器回应的标头,然后空一行,再输出网页的源码。

-I 选项:
-I参数向服务器发出 HEAD 请求,然会将服务器返回的 HTTP 标头打印出来。

$ curl -I https://www.example.com
上面命令输出服务器对 HEAD 请求的回应。

--head参数等同于-I。

$ curl --head https://www.example.com
-k 参数:
-k参数指定跳过 SSL 检测。

$ curl -k https://www.example.com
上面命令不会检查服务器的 SSL 证书是否正确。

-L 参数:
-L参数会让 HTTP 请求跟随服务器的重定向。curl 默认不跟随重定向。

$ curl -L -d 'tweet=hi' https://api.twitter.com/tweet
--limit-rate 选项:
--limit-rate用来限制 HTTP 请求和回应的带宽,模拟慢网速的环境。

$ curl --limit-rate 200k https://google.com
上面命令将带宽限制在每秒 200K 字节。

-o 选项:
-o参数将服务器的回应保存成文件,等同于wget命令。

$ curl -o example.html https://www.example.com
上面命令将www.example.com保存成example.html。

-O 选项:
-O参数将服务器回应保存成文件,并将 URL 的最后部分当作文件名。

$ curl -O https://www.example.com/foo/bar.html
上面命令将服务器回应保存成文件,文件名为bar.html。

-s 选项:
-s参数将不输出错误和进度信息。

$ curl -s https://www.example.com
上面命令一旦发生错误,不会显示错误信息。不发生错误的话,会正常显示运行结果。

如果想让 curl 不产生任何输出,可以使用下面的命令。

$ curl -s -o /dev/null https://google.com
-S 选项:
-S参数指定只输出错误信息,通常与-s一起使用。

$ curl -s -o /dev/null https://google.com
上面命令没有任何输出,除非发生错误。

-u 选项:
-u参数用来设置服务器认证的用户名和密码。

$ curl -u 'bob:12345' https://google.com/login
上面命令设置用户名为bob,密码为12345,然后将其转为 HTTP 标头Authorization: Basic Ym9iOjEyMzQ1。

curl 能够识别 URL 里面的用户名和密码。

$ curl https://bob:12345@google.com/login
上面命令能够识别 URL 里面的用户名和密码,将其转为上个例子里面的 HTTP 标头。

$ curl -u 'bob' https://google.com/login
上面命令只设置了用户名,执行后,curl 会提示用户输入密码。

-v 选项:
-v参数输出通信的整个过程,用于调试。

$ curl -v https://www.example.com
--trace参数也可以用于调试,还会输出原始的二进制数据。

$ curl --trace - https://www.example.com
-x 选项:
-x参数指定 HTTP 请求的代理。

$ curl -x socks5://james:cats@myproxy.com:8080 https://www.example.com
上面命令指定 HTTP 请求通过myproxy.com:8080的 socks5 代理发出。

如果没有指定代理协议,默认为 HTTP。

$ curl -x james:cats@myproxy.com:8080 https://www.example.com
上面命令中,请求的代理使用 HTTP 协议。

-X 选项:
-X参数指定 HTTP 请求的方法。

$ curl -X POST https://www.example.com
上面命令对https://www.example.com发出 POST 请求。
#56
PHP 开发 / PHP CURL中CURLOPT_CONNECTTIMEOU...
上次发布者 cloud - 2022-5月-23 03:11 下午
写了一个简单的curl请求

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200); //限制响应时间200毫秒
$data = curl_exec($ch);
curl_close($ch);

再A服务器运行没有然后问题,到了B服务器发现$data返回false
这就令我百思不得其解了?
来我们开始排坑

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200); //限制响应时间200毫秒
$data = curl_exec($ch);
if($data === false){ //抓取错误信息
     print_r('---------------------start------------------------'.PHP_EOL);
     var_dump(curl_errno($ch));
     var_dump(curl_error($ch));
     print_r('---------------------end------------------------');
    exit();
}
curl_close($ch);
然后我们发现它告诉我们errno:28 超时了!!!
超时了那好解决啊,想当然的我把超时时间从200ms提升倒了600ms,要知道我们这个接口测试的时候是直接绑定host,响应也是直接返回一个json数据.600ms绝对足够了.

curl_setopt($ch, CURLOPT_TIMEOUT_MS, 600); //限制响应时间600毫秒
还是超时!
这就有点不对劲了!
继续修改时间

curl_setopt($ch, CURLOPT_TIMEOUT, 1); //限制响应时间1秒
成功了!那么问题就出在CURLOPT_TIMEOUT_MS上面了!

原来 CURLOPT_CONNECTTIMEOUT_MS 的等待的时间,以毫秒为单位。
真确的开启方式是

    curl_setopt($ch, CURLOPT_NOSIGNAL, true);//libcurl支持毫秒
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
#57
PHP框架-Yii / 数据格式
上次发布者 jvip_chen - 2022-5月-22 05:38 下午
数据格式取决于 HTTP 消息内容组合或解析的方式,例如: 它将确定 yii\httpclient\Message::$data 通过何种方式转换为 yii\httpclient\Message::$content,反之亦然。

默认情况下支持以下格式:

  • yii\httpclient\Client::FORMAT_JSON - JSON format
  • yii\httpclient\Client::FORMAT_URLENCODED - urlencoded by RFC1738 query string
  • yii\httpclient\Client::FORMAT_RAW_URLENCODED - urlencoded by PHP_QUERY_RFC3986 query string
  • yii\httpclient\Client::FORMAT_XML - XML format
每个格式由2个实体覆盖: "formatter" 和 "parser" 。 Formatter 决定请求中数据的组成方式。 Parser 决定如何将原始响应内容解析为数据。

yii\httpclient\Client 自动为上述所有格式选择相应的 formatter 和 parser 。 但是,可以使用 yii\httpclient\Client::$formatters 和 yii\httpclient\Client::$parsers 更改此行为。 可以使用这些字段添加自定义格式或更改标准的格式。 例如:

use yii\httpclient\Client;

$client = new Client([
    'formatters' => [
        'myformat' => 'app\components\http\MyFormatter', // add new formatter
        Client::FORMAT_XML => 'app\components\http\MyXMLFormatter', // override default XML formatter
    ],
]);
在创建自定义的解析器时,应该实现 yii\httpclient\ParserInterface ,同时创建formatter - yii\httpclient\FormatterInterface。 例如:

use yii\httpclient\FormatterInterface;
use yii\httpclient\ParserInterface;
use yii\httpclient\Response;

class ParserIni implements ParserInterface
{
    public function parse(Response $response)
    {
        return parse_ini_string($response->content);
    }
}

class FormatterIni implements FormatterInterface
{
    public function format(Request $request)
    {
        $request->getHeaders()->set('Content-Type', 'text/ini   ; charset=UTF-8');

        $pairs = []
        foreach ($request->data as $name => $value) {
            $pairs[] = "$name=$value";
        }

        $request->setContent(implode("\n", $pairs));
        return $request;
    }
}
#58
PHP框架-Yii / 批量 request 请求
上次发布者 jvip_chen - 2022-5月-22 05:37 下午
可以使用 yii\httpclient\Client::batchSend() 方法同时发送多个请求:

use yii\httpclient\Client;

$client = new Client();

$requests = [
    $client->get('http://domain.com/keep-alive'),
    $client->post('http://domain.com/notify', ['userId' => 12]),
];
$responses = $client->batchSend($requests);
可使用特定的 传输方式 提升其性能。 在内置传输中,只有 yii\httpclient\CurlTransport 允许并行发送请求,从而减少程序执行时间。

注意:只有某些特定的传输传输方式可以使用 batchSend() 并行发送请求。 默认情况下,请求只是一个接一个地发送,没有任何错误或警告抛出。如果需要提升性能 ,则需为客户端配置正确的传输方式。

batchSend() 方法返回响应数组,这些键对应于请求数组中的键。 可以使用如下方式简化响应的处理:

use yii\httpclient\Client;

$client = new Client();

$requests = [
    'news' => $client->get('http://domain.com/news'),
    'friends' => $client->get('http://domain.com/user/friends', ['userId' => 12]),
    'newComment' => $client->post('http://domain.com/user/comments', ['userId' => 12, 'content' => 'New comment']),
];
$responses = $client->batchSend($requests);

// result of `GET http://domain.com/news` :
if ($responses['news']->isOk) {
    echo $responses['news']->content;
}

// result of `GET http://domain.com/user/friends` :
if ($responses['friends']->isOk) {
    echo $responses['friends']->content;
}

// result of `POST http://domain.com/user/comments` :
if ($responses['newComment']->isOk) {
    echo "Comment has been added successfully";
}
#59
PHP框架-Yii / Request 参数
上次发布者 jvip_chen - 2022-5月-22 05:36 下午
使用 yii\httpclient\Request::$options 来调整特定的请求。 支持以下参数:

  • timeout: integer, 允许执行请求的最大超时时间(秒)。
  • proxy: string, 指定代理服务器的地址的 URI。(例如 tcp://proxy.example.com:5100)
  • userAgent: string, 在 HTTP 请求中使用的 "User-Agent:" 标头的内容。
  • followLocation: boolean, 是否重定向至 HTTP 头信息中的任意 "Location:"。
  • maxRedirects: integer, 要跟踪的重定向的最大数量。
  • sslVerifyPeer: boolean, 是否启用 ssl 验证。
  • sslCafile: string, CA 证书在本地文件系统上的位置,应与 'sslVerifyPeer' 参数一起使用以验证服务端的身份。
  • sslCapath: string, 一个保存多个CA证书的目录。
例如:

use yii\httpclient\Client;

$client = new Client();

$response = $client->createRequest()
    ->setMethod('POST')
    ->setUrl('http://domain.com/api/1.0/users')
    ->setData(['name' => 'John Doe', 'email' => 'johndoe@domain.com'])
    ->setOptions([
        'proxy' => 'tcp://proxy.example.com:5100', // use a Proxy
        'timeout' => 5, // set timeout to 5 seconds for the case server is not responding
    ])
    ->send();
提示:可以通过 yii\httpclient\Client::$requestConfig 对默认请求进行设置。 可以使用 yii\httpclient\Request::addOptions() 在添加其他设置的同时保留原始的其他参数。

在使用 yii\httpclient\CurlTransport 时,可配置特殊的请求参数。 例如:指定 cUrl 请求的连接和接收数据的超时时间:

use yii\httpclient\Client;

$client = new Client([
    'transport' => 'yii\httpclient\CurlTransport' // only cURL supports the options we need
]);

$response = $client->createRequest()
    ->setMethod('POST')
    ->setUrl('http://domain.com/api/1.0/users')
    ->setData(['name' => 'John Doe', 'email' => 'johndoe@domain.com'])
    ->setOptions([
        CURLOPT_CONNECTTIMEOUT => 5, // connection timeout
        CURLOPT_TIMEOUT => 10, // data receiving timeout
    ])
    ->send();
有关特定参数支持的详细信息,请参阅特定的传输类文档。
#60
PHP 开发 / PHP——curl使用代理
上次发布者 jvip_chen - 2022-5月-22 04:08 下午
代码样例
使用代理

<?php
//要访问的目标页面
$page_url "http://dev.kdlapi.com/testproxy";

//代理ip,由快代理提供
$proxy "47.115.5.19";
$prod 16816;

$ch curl_init();
curl_setopt($chCURLOPT_URL$page_url);

curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);  
curl_setopt($chCURLOPT_SSL_VERIFYHOSTFALSE);

//设置代理
curl_setopt($chCURLOPT_PROXYTYPECURLPROXY_HTTP);
curl_setopt($chCURLOPT_PROXY$proxy);
curl_setopt($chCURLOPT_PROXYPORT$prod); 

//自定义header
$headers = array();
$headers[] = 'User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0);';
curl_setopt($chCURLOPT_HTTPHEADER$headers);

//自定义cookie
curl_setopt($chCURLOPT_COOKIE,''); 

curl_setopt($chCURLOPT_ENCODING'gzip'); //使用gzip压缩传输数据让访问更快

curl_setopt($chCURLOPT_CONNECTTIMEOUT5);
curl_setopt($chCURLOPT_TIMEOUT10);

curl_setopt($chCURLOPT_HEADERtrue);
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);

$result curl_exec($ch);
$info curl_getinfo($ch);
curl_close($ch);

echo 
$result;
echo 
"\n\nfetch ".$info['url']."\ntimeuse: ".$info['total_time']."s\n\n";
?>
运行下
php curl.php