PHP 系列 (三)

CURL 模拟登录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
$data = [
'email' => 'test@126.com',
'password' => '123456',
];
// 模拟登录
$cookie = __DIR__ . '/cookie.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 连接结束后,保存 cookie 信息的文件
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);

// 采集数据
$url = 'http://xxx.com/login';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 包含 cookie 数据的文件
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
$result = curl_exec($ch);
$result = json_decode($result, true, JSON_UNESCAPED_UNICODE);
var_dump($result);

通过 SSH 拷贝远程文件至本地

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php

class SSH2
{
/**
* @var resource
*/
private $ssh;

/**
* SSH2 constructor.
*
* @param string $host
* @param int $port
* @param string $username
* @param string $password
*/
public function __construct(string $host, int $port, string $username, string $password)
{
$this->ssh = ssh2_connect($host, $port);
ssh2_auth_password($this->ssh, $username, $password);
}

/**
* Exec.
*
* @param string $command
*
* @return bool|string
*/
public function exec(string $command)
{
$stream = ssh2_exec($this->ssh, $command);
stream_set_blocking($stream, true);

return stream_get_contents($stream);
}

/**
* Scp send.
*
* @param string $local
* @param string $remote
* @param int|null $mode
*
* @return bool
*/
public function scpSend(string $local, string $remote, ?int $mode = null)
{
return ssh2_scp_send($this->ssh, $local, $remote, $mode);
}

/**
* Scp recv.
*
* @param string $remote
* @param string $local
*
* @return bool
*/
public function scpRecv(string $remote, string $local)
{
return ssh2_scp_recv($this->ssh, $remote, $local);
}
}

try {
$ip = '192.168.0.77';
$username = 'root';
$password = 'root';
$ssh2 = new SSH2($ip, 22, $username, $password);
// 打包远程文件
$ssh2->exec('cd /data/backup && rm -rf backup.zip && zip -r backup.zip ./');
// 拷贝远程文件至本地
$ssh2->scpRecv('/data/backup/backup.zip', 'D:\backup\backup.zip');
} catch (Exception $e) {
exit($e->getMessage());
}
0%