Java calls Linux to query various information scripts summary

Shenkeng warning

  • If you use the shell or the command line to execute the command, there is no problem, but if you use the string type to call in java, there will be some execution without returning results. The reason is guessed that some commands cannot parse the spaces in java and | And other symbols.
    There are two solutions:
  1. Use arrays to pass commands instead of strings, example:
String[] cmd new String[]{
    
    "data","+%Y-%m-%d %H:%M:%S"}
  1. Use sh -c command to make it run as a whole
String[] cmd = new String[]{
    
    "sh","-c","netstat -tulpen|head -2|tail -1"}
  • Invoking the top command in non-interactive mode through other programs or scripts, there will often be an error that the output cannot be obtained:
    top: failed tty get error
    Solution: just add the -b option
  • Use getInputStream in some cases
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

Cannot receive the data output from the command line, modify it to getErrorStream

BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

View error messages when debugging, add watch to IDEA

new BufferedReader(new InputStreamReader(process.getErrorStream())).readLine()

Error message can be found

system message

  1. Current user
whoami
[root@ks-allinone ~]# whoami
root
  1. Operating system version
cat /etc/redhat-release
[root@ks-allinone ~]# cat /etc/redhat-release
CentOS Linux release 7.6.1810 (Core) 
  1. Kernel version
uname -r
[root@ks-allinone ~]# uname -r
3.10.0-957.el7.x86_64
  1. CPU information
cat /proc/cpuinfo | grep  'model name' | head -n 1 | awk -F": " '{print $2}'
[root@ks-allinone ~]# cat /proc/cpuinfo | ag -o '(?<=model name\t: ).*' | head -n 1
Common KVM processor
#表示这个是虚拟机的CPU
  1. The system runs 32-bit or 64-bit
getconf LONG_BIT
[root@ks-allinone ~]# getconf LONG_BIT
64
  1. CPU name
hostname -s
[root@ks-allinone ~]# hostname -s
ks-allinone
  1. Local IPV4 address
ping ${HOSTNAME} -c 1 | grep -o -E [0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+ | head -n 1
[root@ks-allinone ~]# ping ${HOSTNAME} -c 1 | grep -o -E [0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+ | head -n 1
172.16.10.126
  1. Internet IP
curl pip.cip.cc
[root@ks-allinone ~]# curl ip.cip.cc
159.226.5.169
  1. Extranet IP details
curl cip.cc
[root@ks-allinone ~]# curl cip.cc
IP	: 159.226.5.169
地址	: 中国  北京
运营商	: 科技网

数据二	: 北京市 | 中国科学院软件研究所

数据三	: 

URL	: http://www.cip.cc/159.226.5.169
  1. System current time
date "+%Y-%m-%d %H:%M:%S"
[root@ks-allinone ~]# date "+%Y-%m-%d %H:%M:%S"
2020-09-18 10:49:51
  1. System startup time
date -d "$(awk -F. '{print $1}' /proc/uptime) second ago" +"%Y-%m-%d %H:%M:%S"
[root@ks-allinone ~]# date -d "$(awk -F. '{print $1}' /proc/uptime) second ago" +"%Y-%m-%d %H:%M:%S"
2020-09-16 09:18:01
  1. System running time
cat /proc/uptime| awk -F. '{run_days=$1 / 86400;run_hour=($1 % 86400)/3600;run_minute=($1 % 3600)/60;run_second=$1 % 60;printf("系统已运行:%d天%d时%d分%d秒",run_days,run_hour,run_minute,run_second)}'
[root@ks-allinone ~]# cat /proc/uptime| awk -F. '{run_days=$1 / 86400;run_hour=($1 % 86400)/3600;run_minute=($1 % 3600)/60;run_second=$1 % 60;printf("系统已运行:%d天%d时%d分%d秒",run_days,run_hour,run_minute,run_second)}'
系统已运行:2天1时36分15秒

Host account related

  1. Log in user account
  • ag quick search version
cat /etc/passwd | ag -v 'nologin$|false$'
[root@ks-allinone ~]# cat /etc/passwd | ag -v 'nologin$|false$'
root:x:0:0:root:/root:/bin/bash
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
iscas:x:1000:1000:iscas:/home/iscas:/bin/bash
mysql:x:994:1001::/home/mysql:/bin/bash
mimaceshi:x:1001:1002::/home/mimaceshi:/bin/bash
  • grep general version
cat /etc/passwd|grep -v 'nologin'|awk -F: '{print $1}'
[root@ks-allinone ~]# cat /etc/passwd|grep -v 'nologin'|awk -F: '{print $1}'
root
sync
shutdown
halt
iscas
mysql
mimaceshi
  1. User account details
cat /etc/shadow
[root@ks-allinone ~]# cat /etc/shadow
root:$6$Z/WCDvdGbDCTQknC$PR5ynvhojpao1ZfTTQ/hfk5ckrr0QyPcqCjZfhvWSEwySvh.g7wLxnQ21jrpWCVSRqhr3z7ZbBxGX.jvdsZuh/::0:99999:7:::
bin:*:17834:0:99999:7:::
daemon:*:17834:0:99999:7:::
adm:*:17834:0:99999:7:::
lp:*:17834:0:99999:7:::
sync:*:17834:0:99999:7:::
shutdown:*:17834:0:99999:7:::
halt:*:17834:0:99999:7:::
mail:*:17834:0:99999:7:::
operator:*:17834:0:99999:7:::
games:*:17834:0:99999:7:::
ftp:*:17834:0:99999:7:::
nobody:*:17834:0:99999:7:::
systemd-network:!!:18435::::::
dbus:!!:18435::::::
polkitd:!!:18435::::::
sshd:!!:18435::::::
postfix:!!:18435::::::
chrony:!!:18435::::::
iscas:$6$XIdrm7XJCnk2/kC.$AgjV0ZdYiYUlLaa4oTiFQxCby1YmZd4CrklDladz75agHep8tQlS0RTS77YF7wGxf7vOOOh/wPLx/vOUYAaBe1::0:99999:7:::
kube:!!:18463::::::
etcd:!!:18463::::::
gluster:!!:18463::::::
rpc:!!:18463:0:99999:7:::
rpcuser:!!:18463::::::
nfsnobody:!!:18463::::::
mysql:!!:18467::::::
mimaceshi:$6$4qfOKtYC$QlzooB.QoP0VPF1vKo2AbxZ7Z4rte2/oARPvR8eJgo0Fua.IF9I54jtChXXCeA6ArYGNg8MCM7L6YzM6qnAzR0:18470:0:99999:7:::
tss:!!:18516::::::
  1. User password file modification time
  • ag quick search version
stat /etc/passwd | ag -o '(?<=Modify: ).*' --nocolor
[root@ks-allinone ~]# stat /etc/passwd | ag -o '(?<=Modify: ).*' --nocolor
2020-09-11 09:48:24.250529573 +0800
  • grep general version
stat /etc/passwd | grep  Modify:| awk -F": " '{print $2}'
[root@ks-allinone ~]# stat /etc/passwd | grep  Modify:| awk -F": " '{print $2}'
2020-09-22 09:28:55.965597644 +0800
  1. User with sudo privileges
  • ag initial quick search version
cat /etc/sudoers | grep -v '#' | sed -e '/^$/d' | ag ALL --nocolor
[root@ks-allinone ~]# cat /etc/sudoers | grep -v '#' | sed -e '/^$/d' | ag ALL --nocolor
Defaults    env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
root	ALL=(ALL) 	ALL
%wheel	ALL=(ALL)	ALL
  • Grep general version, extracted key information
cat /etc/sudoers | grep -v '#' | sed -e '/^$/d' | grep ALL= | awk '{print $1}'
[root@ks-allinone ~]# cat /etc/sudoers | grep -v '#' | sed -e '/^$/d' | grep ALL= | awk '{print $1}'
root
%wheel
  1. Special account UID is 0
awk -F: '{ if($3 == 0 && $1 != "root") print $1 }' /etc/passwd
  1. Special account GID is 0
awk -F: '{ if($4 == 0 && $1 != "root") print $1 }' /etc/passwd
[root@ks-allinone ~]# awk -F: '{ if($4 == 0 && $1 != "root") print $1 }' /etc/passwd
sync
shutdown
halt
operator
  1. Account that can log in to Shell
cat /etc/passwd|grep -v nologin|grep -v sync|grep -v halt|grep -v shutdown|awk -F":" '{ print $1"|"$3"|"$4 }'|more
[root@ks-allinone ~]# cat /etc/passwd|grep -v nologin|grep -v sync|grep -v halt|grep -v shutdown|awk -F":" '{ print $1"|"$3"|"$4 }'|more
root|0|0
iscas|1000|1000
mysql|994|1001
mimaceshi|1001|1002

Host port related

  1. Port monitoring
netstat -tulpen |head -2;netstat -tulpen | ag 'tcp|udp.*' --nocolor
[root@ks-allinone ~]# netstat -tulpen |head -2;netstat -tulpen | ag 'tcp|udp.*' --nocolor
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       User       Inode      PID/Program name  
tcp        0      0 127.0.0.1:10248         0.0.0.0:*               LISTEN      0          45587      8117/kubelet        
tcp        0      0 169.254.25.10:9254      0.0.0.0:*               LISTEN      0          96808      12028/node-cache    
tcp6       0      0 :::9353                 :::*                    LISTEN      0          93735      12028/node-cache    
tcp6       0      0 :::30180                :::*                    LISTEN      0          96496      11493/kube-proxy    
tcp6       0      0 :::9253                 :::*                    LISTEN      0          96809      12028/node-cache      
udp        0      0 0.0.0.0:774             0.0.0.0:*                           0          33822      5267/rpcbind             
udp6       0      0 :::774                  :::*                                0          33825      5267/rpcbind   

grep version

netstat -tulpen |head -2|tail -1;netstat -tulpen | grep -E 'tcp|udp'
  1. Open port
netstat -tulpen | awk '{print $1,$4}' | ag -o '.*0.0.0.0:(\d+)' --nocolor
[root@ks-allinone ~]# netstat -tulpen | awk '{print $1,$4}' | ag -o '.*0.0.0.0:(\d+)' --nocolor
tcp 0.0.0.0:111
tcp 0.0.0.0:22
udp 0.0.0.0:111
udp 0.0.0.0:123
udp 0.0.0.0:774

grep version

netstat -tulpen | awk '{print $1,$4}' | grep '0.0.0.0'
  1. Query the service corresponding to the port
cat /etc/services

Process related

  1. View running process
ps -ef
[root@ks-allinone ~]# ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  1 Sep16 ?        00:55:21 /usr/lib/systemd/systemd --switched-root --system --deserialize 22
root         2     0  0 Sep16 ?        00:00:00 [kthreadd]
root         3     2  0 Sep16 ?        00:01:15 [ksoftirqd/0]
root         5     2  0 Sep16 ?        00:00:00 [kworker/0:0H]
  1. The specified information of the screening process.
    Adjust the cmd order and put it at the end to deal with the regularity.
ps -eo pid,ppid,user,group,stat,tty,time,cmd
[root@ks-allinone ~]# ps -eo pid,ppid,user,group,cmd,stat,tty,time
  PID  PPID USER     GROUP    CMD                         STAT TT           TIME
    1     0 root     root     /usr/lib/systemd/systemd -- Ss   ?        01:20:49
    2     0 root     root     [kthreadd]                  S    ?        00:00:00
    3     2 root     root     [ksoftirqd/0]               S    ?        00:01:52
    5     2 root     root     [kworker/0:0H]              S<   ?        00:00:00
    7     2 root     root     [migration/0]               S    ?        00:00:18
    8     2 root     root     [rcu_bh]                    S    ?        00:00:00
  1. View the parent-child process relationship
ps -e  --forest
[root@ks-allinone ~]# ps -e  --forest
        PID TTY          TIME CMD
          2 ?        00:00:13 kthreadd
          4 ?        00:00:00  \_ kworker/0:0H
          6 ?        00:11:22  \_ ksoftirqd/0
          7 ?        00:01:30  \_ migration/0
          8 ?        00:00:00  \_ rcu_bh
          9 ?        03:43:00  \_ rcu_sched
         10 ?        00:00:00  \_ lru-add-drain
         11 ?        00:00:20  \_ watchdog/0
         12 ?        00:00:18  \_ watchdog/1

Host resource consumption

  1. CPU occupancy
    The b parameter is added because: when the top command is invoked in non-interactive mode through other programs or scripts, the top: failed tty get error often occurs
top -bn 1 | grep Cpu
[root@ks-allinone ~]# top -bn 1 | grep Cpu
%Cpu(s):  4.4 us,  8.0 sy,  0.0 ni, 87.1 id,  0.0 wa,  0.0 hi,  0.4 si,  0.0 st
  1. Memory footprint
free -mh
[root@ks-allinone ~]# free -mh
              total        used        free      shared  buff/cache   available
Mem:            62G         13G         30G        647M         19G         45G
Swap:            0B          0B          0B
  1. Hard drive occupation

Detailed occupancy

df -mhT
[root@ks-allinone ~]# df -mhT
Filesystem              Type      Size  Used Avail Use% Mounted on
/dev/mapper/centos-root xfs        50G   36G   15G  72% /
/dev/sda1               xfs      1014M  217M  798M  22% /boot
/dev/mapper/centos-home xfs        62G   10G   52G  17% /home

More detailed information

fdisk -l | grep Disk
[root@ks-allinone ~]# fdisk -l | grep Disk
Disk /dev/sda: 128.8 GB, 128849018880 bytes, 251658240 sectors
Disk label type: dos
Disk identifier: 0x000e2fc4
Disk /dev/mapper/centos-root: 53.7 GB, 53687091200 bytes, 104857600 sectors
Disk /dev/mapper/centos-home: 65.6 GB, 65624080384 bytes, 128172032 sectors

Tree structure display

lsblk
[root@ks-allinone ~]# lsblk
NAME            MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda               8:0    0  120G  0 disk 
├─sda1            8:1    0    1G  0 part /boot
└─sda2            8:2    0  119G  0 part 
  ├─centos-root 253:0    0   50G  0 lvm  /
  └─centos-home 253:2    0 61.1G  0 lvm  /home
sr0              11:0    1 1024M  0 rom  
  1. Hard disk mounting situation
cat /etc/fstab | ag -v "#" | awk '{print $1,$2,$3}'
[root@ks-allinone ~]# cat /etc/fstab | ag -v "#" | awk '{print $1,$2,$3}'
/dev/mapper/centos-root / xfs
UUID=e09b1921-3121-4f06-9c58-54d2dae390a6 /boot xfs
/dev/mapper/centos-home /home xfs

grep version

cat /etc/fstab | grep -v "#" | awk '{print $1,$2,$3}'
  1. CPU and memory usage TOP rankings
ps aux |head -1;ps aux| grep -v ^'USER' | sort -rn -k3 | head -5
[root@ks-allinone ~]# ps aux |head -1;ps aux| grep -v ^'USER' | sort -rn -k3 | head -5
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root      8117 15.6  0.2 2688896 152232 ?      Ssl  Sep16 494:25 /usr/local/bin/kubelet --logtostderr=true --v=2 --node-ip=172.16.10.126 --hostname-override=ks-allinone --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --config=/etc/kubernetes/kubelet-config.yaml --kubeconfig=/etc/kubernetes/kubelet.conf --rotate-certificates --pod-infra-container-image=mirrorgooglecontainers/pause-amd64:3.1 --runtime-cgroups=/systemd/system.slice --kube-reserved cpu=200m,memory=512M --system-reserved cpu=250m,memory=256M --node-labels= --feature-gates=CSINodeInfo=true,VolumeSnapshotDataSource=true,ExpandCSIVolumes=true,RotateKubeletClientCertificate=true --network-plugin=cni --cni-conf-dir=/etc/cni/net.d --cni-bin-dir=/opt/cni/bin
root      5785 13.6  0.2 2516320 144320 ?      Ssl  Sep16 432:25 /usr/bin/dockerd --registry-mirror=https://dockerhub.azk8s.cn --data-root=/var/lib/docker --log-opt max-size=10m --log-opt max-file=3 --insecure-registry=172.16.10.126
root      9238  5.9  0.7 1523220 481328 ?      Ssl  Sep16 187:43 kube-apiserver --advertise-address=172.16.10.126 --allow-privileged=true --anonymous-auth=True --apiserver-count=1 --authorization-mode=Node,RBAC --bind-address=0.0.0.0 --client-ca-file=/etc/kubernetes/ssl/ca.crt --enable-admission-plugins=NodeRestriction --enable-aggregator-routing=False --enable-bootstrap-token-auth=true --endpoint-reconciler-type=lease --etcd-cafile=/etc/ssl/etcd/ssl/ca.pem --etcd-certfile=/etc/ssl/etcd/ssl/node-ks-allinone.pem --etcd-keyfile=/etc/ssl/etcd/ssl/node-ks-allinone-key.pem --etcd-servers=https://172.16.10.126:2379 --feature-gates=CSINodeInfo=true,VolumeSnapshotDataSource=true,ExpandCSIVolumes=true,RotateKubeletClientCertificate=true --insecure-port=0 --kubelet-client-certificate=/etc/kubernetes/ssl/apiserver-kubelet-client.crt --kubelet-client-key=/etc/kubernetes/ssl/apiserver-kubelet-client.key --kubelet-preferred-address-types=InternalDNS,InternalIP,Hostname,ExternalDNS,ExternalIP --profiling=False --proxy-client-cert-file=/etc/kubernetes/ssl/front-proxy-client.crt --proxy-client-key-file=/etc/kubernetes/ssl/front-proxy-client.key --request-timeout=1m0s --requestheader-allowed-names=front-proxy-client --requestheader-client-ca-file=/etc/kubernetes/ssl/front-proxy-ca.crt --requestheader-extra-headers-prefix=X-Remote-Extra- --requestheader-group-headers=X-Remote-Group --requestheader-username-headers=X-Remote-User --runtime-config= --secure-port=6443 --service-account-key-file=/etc/kubernetes/ssl/sa.pub --service-cluster-ip-range=10.233.0.0/18 --service-node-port-range=30000-32767 --storage-backend=etcd3 --tls-cert-file=/etc/kubernetes/ssl/apiserver.crt --tls-private-key-file=/etc/kubernetes/ssl/apiserver.key
root     12028  5.9  0.0 117864 18936 ?        Ssl  Sep16 187:08 /node-cache -localip 169.254.25.10 -conf /etc/coredns/Corefile
root     28901  5.4 13.4 14423140 8876756 ?    Sl   Sep16 168:16 /usr/local/jdk/bin/java -server -Xms8g -Xmx8g -Xmn4g -XX:+UseG1GC -XX:G1HeapRegionSize=16m -XX:G1ReservePercent=25 -XX:InitiatingHeapOccupancyPercent=30 -XX:SoftRefLRUPolicyMSPerMB=0 -verbose:gc -Xloggc:/dev/shm/mq_gc_%p.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCApplicationStoppedTime -XX:+PrintAdaptiveSizePolicy -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=5 -XX:GCLogFileSize=30m -XX:-OmitStackTraceInFastThrow -XX:+AlwaysPreTouch -XX:MaxDirectMemorySize=15g -XX:-UseLargePages -XX:-UseBiasedLocking -Djava.ext.dirs=/usr/local/jdk/jre/lib/ext:/home/rocketmq/bin/../lib -cp .:/home/rocketmq/bin/../conf:/usr/local/jdk/lib:/usr/local/jdk/jre/lib: org.apache.rocketmq.broker.BrokerStartup -c ../conf/broker.conf autoCreateTopicEnable=true

App installation status and version

  1. Installed application software version
rpm -qa
[root@ks-allinone ~]# rpm -qa
python-setuptools-0.9.8-7.el7.noarch
grub2-2.02-0.76.el7.centos.x86_64
kbd-legacy-1.15.5-15.el7.noarch
apr-1.4.8-5.el7.x86_64
NetworkManager-wifi-1.12.0-6.el7.x86_64
ncurses-base-5.9-14.20130511.el7_4.noarch
perl-HTTP-Tiny-0.033-3.el7.noarch
postfix-2.10.1-7.el7.x86_64
perl-Text-ParseWords-3.29-4.el7.noarch
aic94xx-firmware-30-6.el7.noarch
  1. ssh service version
ssh -V
[root@ks-allinone ~]# ssh -V
OpenSSH_7.4p1, OpenSSL 1.0.2k-fips  26 Jan 2017

Host system security

  1. Patch version query
patch -v 
[root@ks-allinone ~]# patch -v|head -1
GNU patch 2.7.1
  1. Weak password query
[root@ks-allinone run]# ./john /etc/passwd /etc/shadow
Loaded 3 password hashes with 3 different salts (crypt, generic crypt(3) [?/64])
Press 'q' or Ctrl-C to abort, almost any other key for status
iscas123         (iscas)
iscas123         (root)

See the blog for details of weak passwords
https://blog.csdn.net/wenyichuan/article/details/107612023

Guess you like

Origin blog.csdn.net/wenyichuan/article/details/108660699