Created
August 31, 2011 09:03
-
-
Save HungYuHei/1183126 to your computer and use it in GitHub Desktop.
干掉ssh同一用户多个登录脚本
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/php | |
<?php | |
kickearlyuser(); | |
function kickearlyuser() { | |
$usernames = array(); | |
$pids = array(); | |
$um = new shell(); | |
$res = $um->ps('sshd:'); | |
foreach ($res as $row) { | |
$arr = explode(' ', $row); | |
//整理 | |
$cnt = count($arr); | |
$new_arr = array(); | |
for ($i = 0; $i < $cnt; $i++) { | |
if (!empty($arr[$i])) { | |
$new_arr[] = $arr[$i]; | |
} | |
} | |
//搜索sshd | |
$index = array_search('sshd:', $new_arr); | |
//ps进程去掉 | |
if ($index == count($new_arr) - 1) { | |
continue; | |
} | |
//root@pts/1这样的 | |
$pos = strpos($new_arr[$index + 1], '@'); | |
if ($pos === false) { | |
$len = 300; | |
} else { | |
$len = $pos; | |
} | |
$username = substr($new_arr[$index + 1], 0, $len); | |
//不处理root | |
if ($username == 'root') | |
continue; | |
//只要存在的就比较pid大小,把小的干掉! | |
$k = array_search($username, $usernames); | |
if ($k === false) { | |
$usernames[] = $username; | |
$pids[] = $new_arr[1]; | |
} else { | |
if ($new_arr[1] > $pids[$k]) { | |
$t = $pids[$k]; | |
$usernames[$k] = $username; | |
$pids[$k] = $new_arr[1]; | |
$um->kill($t); | |
} else { | |
$um->kill($new_arr[1]); | |
} | |
} | |
} | |
} | |
class shell { | |
const ps = '/bin/ps'; | |
const kill='/usr/bin/kill'; | |
public function ps($username){ | |
$command[] = self::ps." aux|".self::grep." $username"; | |
return $this->exec($command); | |
} | |
public function kill($pid){ | |
$command = self::kill." -9 ".$pid; | |
return $this->exec($command); | |
} | |
private function exec($command) { | |
$res = array(); | |
if (is_array($command)) { | |
foreach ($command as $cmd) { | |
//echo $cmd.""; | |
exec($cmd, &$res); | |
} | |
} else { | |
//echo $command."\n"; | |
exec($command, &$res); | |
} | |
return $res; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment