我正在尝试使用内置SSH功能的Laravel从远程服务器获取git日志。一切正常但通过SSH连接需要大约7秒钟,获取日志,将提交转换为数组,然后在视图中显示它们。我不知道它是否正常,或者我需要另一种方法,可能是python,cgi ...... 这是我到目前为止的功能:
public function commits(){
$commands = array(
'cd /var/www/web1/public_html',
'git log -8',
);
SSH::into('production')->run($commands, function($line)
{
$this->output .= $line.PHP_EOL;
});
$arr = explode("\n",$this->output);
foreach ($arr as $line){
// Clean Line
$line = trim($line);
// Proceed If There Are Any Lines
if (!empty($line))
{
// Commit
if (strpos($line, 'commit') !== false)
{
$hash = explode(' ', $line);
$hash = trim(end($hash));
$git_history[$hash] = [
'message' => ''
];
$last_hash = $hash;
$git_history[$last_hash]['hash'] = $last_hash;
}
// Author
else if (strpos($line, 'Author') !== false) {
$author = explode(':', $line);
$author = trim(end($author));
//email starts with < and ends with >
$pattern = sprintf(
'/%s(.+?)%s/ims',
preg_quote('<', '/'), preg_quote('>', '/')
);
//check pattern and assign the email of the author
if (preg_match($pattern, $author, $matches)) {
list(, $match) = $matches;
//echo $match;
$git_history[$last_hash]['author'] = $match;
$user = Sentry::findUserByLogin($git_history[$last_hash]['author']);
$git_history[$last_hash]['avatar'] = $user->avatar;
}
}
// Date
else if (strpos($line, 'Date') !== false) {
$date = explode(':', $line, 2);
$date = trim(end($date));
$git_history[$last_hash]['date'] = date('d/m/Y H:i:s A', strtotime($date));
}
// Message
else {
$git_history[$last_hash]['message'] .= $line ." ";
}
}
}
//$data['server_answer'] = $git_history;
return Response::json($git_history);
}
答案 0 :(得分:1)
我通常使用Paramiko,它更容易
import paramiko
# ssh
print 'enter ssh'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # this will automatically add the keys
ssh.connect(machineHostName, username=user, password=password)
# Run your commands
# example 1 : ls command
print 'do a ls command'
stdin, stdout, stderr = ssh.exec_command('ls')
print stdout.readlines()
time.sleep(2)
# example 2 : change ip address
print 'changing ip address'
stdin, stdout, stderr = ssh.exec_command('sed -i -- s/'+oldIp+'/'+newIp+'/g /etc/sysconfig/network-scripts/ifcfg-eth0')
print stdout.readlines()
time.sleep(2)
要安装Paramiko,您可以从here下载tar.gz文件。
假设你真的是python的新手,如何安装:
tar.gz
文件cd
从您的终端python setup.py install
注意:如果你在这里遇到安装评论,我可以帮助你。
答案 1 :(得分:0)
我最终构建了一个python API,用于在服务器中执行命令,而不是通过SSH连接,因为使用带有PHP的SSH库会减慢网站的速度。使用python执行命令并返回消息/错误它会快得多(不到1秒)。