Linux(centos)禁止root用户直接登录sshd并修改默认端口

新建一个帐号

#创建用户 
adduser yourusername 
#设置密码 
passwd yourusernamepassword 

给用户添加sudo权限

#切换到root用户下,执行 
visudo 
#找到root ALL=(ALL) ALL这一行,在下面加上 
yourusername ALL=(ALL) ALL 
# :wq保存并退出 

测试是否成功

su yourusername 
cd ~ 
sudo mkdir test 
#输入密码后成功创建代表设置成功 

修改SSHD配置,禁止root直接登录

vi /etc/ssh/sshd_config 
#找到#PermitRootLogin yes”将yes该外no 
PermitRootLogin no 
#找到#Port 22字段删掉#,将22改为其他不被使用的端口 
Port XXXX 

重启sshd服务

service sshd restart 

重要提醒:这时切莫退出服务器。你要测试能不能使用刚创建的用户成功地通过ssh进入到服务器。打开终端的另一个实例,以之前创建的用户通过ssh进入到服务器。要是一切都正常,你可以以根用户身份安全地注销退出服务器。

Linux CentOS升级Python 3.6版本方法

由于软件环境的需要较高版本的python,默认CentOS6是2.6版本,CentOS7是2.7版本。这里要顺带提一下,有网友提到在CentOS6中无法安装Seafile云盘一键包的原因,因为需要默认最低是Python2.7版本才可以。而且在这篇文章中,老左调试的一个软件需要Python3以上版本,所以我准备安装Python 3.6。
备注:建议我们不熟悉的网友不要直接在生产环境中直接安装,可以先在测试环境安装看看是否可行。

第一、安装必备环境包

yum -y groupinstall development zlib zlib-devel

未分类

第二、下载和安装python3.6

wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz
tar xJf Python-3.6.0.tar.xz
cd Python-3.6.0
./configure
make
make install

未分类

第三、检查是否成功

which python3
python3 -V

未分类

第四、创建软链接

cd /usr/bin
mv python python.backup
ln -s /usr/local/bin/python3 /usr/bin/python

然后我们重启下机器,再看看当前的python是不是3.6
未分类
这样python可以升级安装到3.6版本。

Linux CentOS环境下单机安装tomcat多实例

平台: centos 6.9
安装版本:tomcat 9.0 Binary Distributions

安装目的:安装三个tomcat,对外 web端口分别为8080、8081、8082
原理: 多个tomcat实例公用一个JDK,通过安装目录、端口以及配置文件实现独立实例,每个tomcat猫 都有自己独立的运行环境、配置文件 和站点目录。

按照系统的部署流程记录如下:

1、安装JDK

yum search java,这里我们选取java-1.8.0-openjdk.x86_64 : OpenJDK Runtime Environment。

yum install java-1.8.0-openjdk.x86_64   -y

2、下载安装tomcat

下载地址https://tomcat.apache.org/,这里我们选取tomcat版本后对应下载,以Binary Distributions 9.0做测试。

wget  http://mirrors.shuosc.org/apache/tomcat/tomcat-9/v9.0.1/bin/apache-tomcat-9.0.1.tar.gz   -P  /usr/local/src
cd  /usr/local/src
tar zxvf apache-tomcat-9.0.1.tar.gz 
mv apache-tomcat-9.0.1 tomcat_8080
#说明:这里不建议直接mv到/usr/local目录中,因为这个是原始的tomcat,以后创建多实例可以直接从这里拷贝并优化。
#配置单实例tomcat8080
mkdir  /usr/local/tomcat_8080
cp -rfpu  /usr/local/src/tomcat_8080/* /usr/local/tomcat_8080/

启动tomcat8080:

/usr/local/tomcat_8080/bin/startup.sh

查看效果:

[root@mysqlemn local]# netstat  -tunlp | grep 8080
tcp        0      0 :::8080                     :::*                        LISTEN      13240/java

如果防火墙开启,需要加一个规则进去以便web访问:

iptables  -I  INPUT -p tcp  --dport  8080  -j ACCEPT

web访问测试:

未分类

3、多实例安装

刚才创建了一个8080,下边我们再创建两个tomcat,端口分别为8081、8082。 如果熟练了,可以直接跳过8080,直接创建需要的实例个数。
创建多个tomcat目录:

mkdir -p /usr/local/tomcat_808{1..2}
cp  -rfpu  /usr/locat/src/tomcat_8080/*  /usr/local/tomcat_8081/
cp  -rfpu  /usr/locat/src/tomcat_8080/*  /usr/local/tomcat_8082/

分别修改tomcat的 conf目录下的server.xml,修改三个端口设置(Server、Connector、AJP,至于https根据 是否用到修改),防止和之前的tomcat_8080冲突。修改以后分别启动测试:

/usr/local/tomcat_8081/bin/startup.sh
/usr/local/tomcat_8082/bin/startup.sh

iptables 添加端口并save,web单独访问,单机多实例猫已经实现。剩下的就是根据业务需要、服务器配置进行tomcat的配置优化了,比如包括服务设置、站点发布目录以及 jvm优化等等。

说明:

(1),站点发布目录修改:

未分类

重启tomcat生效。

(2),这里建议将站点目录的catalina.sh设置成tomcatX放于/etc/init.d/tomcatPort ,里边设置下java路径以及环境启动目录比如:

[root@21yunwei ROOT]# cp   /usr/local/tomcat_8080/bin/catalina.sh      /etc/init.d/tomcat8080  -p
[root@21yunwei ROOT]# cp   /usr/local/tomcat_8081/bin/catalina.sh      /etc/init.d/tomcat8081  -p
[root@21yunwei ROOT]# cp   /usr/local/tomcat_8082/bin/catalina.sh      /etc/init.d/tomcat8082  -p

针对每个服务设置自己的启动目录:这里以/etc/init.d/tomcat8080 为例进行修改,第二行加入:

CATALINA_HOME=/usr/local/tomcat_8080 #tomcat容器的启动目录

其他容器的服务也是一样,这样以后就可以通过/etc/init.d/tomcatPort start 启动或者stop了,同时这个可以设置到/etc/rc.local脚本中方便开机启动,目前我们线上就是这样实现。

/etc/init.d/tomcat8080  start
/etc/init.d/tomcat8081  start
/etc/init.d/tomcat8082  start

(3),清理tomcat缓存。解决访问有异常,清理下tomcat服务器端的缓存方法:

find /usr/local/ -name  "work*" | xargs   rm -rf

说明:这里只是针对tomcat安装测试,未进行任何优化。

Linux下配置SSH无密码登录

  • 用ssh-keygen创建公钥
[root@qzweb1 .ssh]# ssh-keygen -t rsa    //生成密钥
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):    //回车,使用默认目录
Enter passphrase (empty for no passphrase):     //直接回车设置空密码           
Enter same passphrase again:            //也是回车
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
e0:be:39:e4:08:a0:4c:e7:16:f5:bc:80:68:14:59:8a root@qzweb1
The key's randomart image is:
+--[ RSA 2048]----+
| .+.             |
|.o.  .           |
|E.. o +          |
|.+ + o +         |
|=.o . o S        |
|...o ...         |
|  .. +.          |
|    . oo         |
|      o.         |
+-----------------+
  • 查看生成出来的密钥
[root@qzweb1 .ssh]# cd ~/.ssh/
[root@qzweb1 .ssh]# ls -l
总用量 12
-rw-------  1 root root 1675 11月 23 15:14 id_rsa
-rw-r--r--  1 root root  393 11月 23 15:14 id_rsa.pub
-rw-r--r--. 1 root root 3176 11月 22 10:45 known_hosts
[root@qzweb1 .ssh]#
  • 下发公钥至目标机器
[root@qzweb1 .ssh]# scp id_rsa.pub 192.168.113.132:~/.ssh/
[email protected]'s password: 
id_rsa.pub                                                                                                                                                                                                                                  100%  393     0.4KB/s   00:00    
[root@qzweb1 .ssh]#
  • 配置目标机并设置文件和目录权限
[root@qzweb2 ~]# cd ~/.ssh/
[root@qzweb2 .ssh]# ls
id_rsa.pub
[root@qzweb2 .ssh]# cat id_rsa.pub >> authorized_keys
[root@qzweb2 .ssh]# chmod 600 authorized_keys  
[root@qzweb2 .ssh]# chmod 700 -R ~/.ssh 
[root@qzweb2 .ssh]#
  • 使用SSH进行连接
[root@qzweb1 .ssh]# ssh 192.168.113.132
Last login: Thu Nov 23 13:42:21 2017 from 192.168.81.24

相关说明

创建的~/.ssh/id_rsa、id_rsa.pub的文件,其中第一个为密钥,第二个为公钥。过程中会要求输入密码,为了ssh访问过程无须密码,可以直接回车。

ssh-keygen:生成秘钥的部分参数:
-t指定算法
-f 指定生成秘钥路径
-N 指定密码

相关说明2

ssh-copy-id 命令可以把本地的ssh公钥文件安装到远程主机对应的账户下。用法:

ssh-copy-id -i /root/.ssh/id_rsa 192.168.1.11

0
The authenticity of host '192.168.1.11 (192.168.1.11)' can't be established.
RSA key fingerprint is 6e:34:d4:8c:fb:72:72:3a:49:7a:14:23:20:59:ea:28.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.11' (RSA) to the list of known hosts.
[email protected]'s password: (输入192.168.1.11 root密码)
Now try logging into the machine, with "ssh '192.168.2.11'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

ssh-copy-id -i /root/.ssh/id_rsa 192.168.1.12
同上

ssh-copy-id -i /root/.ssh/id_rsa 192.168.1.13
同上

sftp上传文件到linux服务器上(ssh验证)

需求:

以前,手动上传配置文件到服务器,然后手工复制到另外一台服务器上,然后登陆SSH Secure File Transfer Client客户端,执行相关shell命令号
现在这些操作需要一键完成,即文件复制到另一台服务器,登陆ssh客户端,切换用户,执行导入命令行
解决办法:

  • 获得应用程序所在的机器用户名和密码,然后执行shell脚本完成以上操作
  • 未采用:因为运维不提供应用服务器的用户名和密码
    直接连接另一台服务器,执行复制文件,然后执行shell脚本(采取)
    要上传文件到linux服务器上,使用FTP协议,公司linux服务器上需要ftp客户端需要安全验证,比较麻烦,所以想到使用sftp来解决,sftp是基于ssh的安全协议的ftp协议,Java中有JSch包来实现连接服务器。

第一步:下载JSch包,请从官网下载它:http://www.jcraft.com/jsch/
第二步:新建FtpsFileList.java文件

//只有上传方法,也可以有下载文件方法
public class FtpsFileList {
    private static final Logger LOG = LoggerFactory.getLogger(FtpsFileList.class);

    //将本地的dirFile这个文件复制到远程服务器上的desFile文件夹下
    public static void loadFile(String host, int port, String username, final String password, String dirFile,String desFile) {
        ChannelSftp sftp = null;
        Channel channel = null;
        Session sshSession = null;
        try {
            JSch jsch = new JSch();//创建一个jsch对象
            jsch.getSession(username, host, port);
            // 根据用户名,主机ip,端口获取一个Session对象
            sshSession = jsch.getSession(username, host, port);
            //设置密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            // 为Session对象设置properties
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            LOG.debug("Session connected!");
            // 打开SFTP通道
            channel = sshSession.openChannel("sftp");
            // 建立SFTP通道的连接
            channel.connect();
            LOG.debug("Channel connected!");
            sftp = (ChannelSftp) channel;

            //InputStream is = sftp.get("/ftp/re/20140713.dat");
            InputStream fis = new FileInputStream(new File(dirFile));
            //文件上传(通过inputstream流来实现)  详见https://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html
            sftp.put(fis,desFile);
            LOG.info("文件复制到服务器成功!r");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeChannel(sftp);
            closeChannel(channel);
            closeSession(sshSession);
        }
    }

    private static void closeChannel(Channel channel) {
        if (channel != null) {
            if (channel.isConnected()) {
                channel.disconnect();
            }
        }
    }

    private static void closeSession(Session session) {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }
}

调用方式:

FtpsFileList.loadFile("10.31.92.70", 22, "serviceop", "115LbUrAbEsZw","/nfsc/qhcs-ansir-stg1/ansir/HanLP/xiaodai/loan-freebase.ttl","/wls/serviceop/virtuoso_script/loanXD.ttl");
logger.info("ttl文件复制成功");

到这一步,已经完成上传文件到linux服务器上

第三步:写好shell脚本(关键核心),这一步学习了好多东西,发现shell命令挺好玩的

#!/usr/bin/expect
spawn ssh [email protected]
set timeout 2
expect "password:"
send "115LbUrAbEsZwr"
expect "*]#"
set password "wuxin952"
spawn su root
expect "password:"  
send "wuxin952r" 
expect "#"
send "/wls/serviceop/virtuoso-opensource/home/bin/isql localhost:13002r" 
send "DB.DBA.TTLP_MT(file_to_string_output('/wls/serviceop/virtuoso_script/loan.ttl'),'','http://www.xiaowei.com');r"
interact

注释:因为需要交互式输入密码,所以选择使用expect命令环境来执行
具体释义见:

第四步:java代码调用shell脚本,代码如下,
Process类是一个抽象类,用于定义一个本地进程,Runtime.getRuntime().exec(sh)返回一个进程对象
具体见:process

//授予权利给shell脚本呢
Process ps1=Runtime.getRuntime().exec("chmod 777 /nfsc/qhcs-ansir-stg1/ansir/HanLP/xiaodai/bash_scp.sh");
//等待当前线程执行完,等待返回process类对象表示的进程结束
ps1.waitFor();
logger.info("chmod命令执行结束");

BufferedReader br1 = new BufferedReader(new InputStreamReader(ps1.getInputStream()));
while ((line = br1.readLine()) != null) {
    logger.info("chmod命令结果:"+line);
}
//实际调用使用expect 文件
Process ps2=Runtime.getRuntime().exec("expect /nfsc/qhcs-ansir-stg1/ansir/HanLP/xiaodai/bash_scp.sh");
ps2.waitFor();
logger.info("expect命令执行结束");

BufferedReader br2 = new BufferedReader(new InputStreamReader(ps2.getInputStream()));
while ((line = br2.readLine()) != null) {
    logger.info("expect命令结果:"+line);
}

String result = sb.toString();
logger.info("expect整理结果为:"+result);

Linux 配置 nginx、mysql、php-fpm、redis 开机启动

Linux(CentOS)上配置 nginx、mysql、php-fpm、redis 开机启动,编写开机启动脚本。

系统环境: CentOS Linux

I、nginx开机启动

1. 在/etc/init.d/目录下创建脚本

vim  /etc/init.d/nginx

2. 更改脚本权限

chmod 775 /etc/init.d/nginx

3. 编写脚本内容

#!/bin/bash
# nginx Startup script for the Nginx HTTP Server
# it is v.0.0.2 version.
# chkconfig: - 85 15
# description: Nginx is a high-performance web and proxy server.
#              It has a lot of features, but it's not for everyone.
# processname: nginx
# pidfile: /var/run/nginx.pid
# config: /usr/local/nginx/conf/nginx.conf
nginxd=/usr/local/webserver/nginx/sbin/nginx
nginx_config=/usr/local/webserver/nginx/conf/nginx.conf
nginx_pid=/usr/local/webserver/nginx/logs/nginx.pid
RETVAL=0
prog="nginx"
# Source function library.
.  /etc/rc.d/init.d/functions
# Source networking configuration.
.  /etc/sysconfig/network
# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0
[ -x $nginxd ] || exit 0
# Start nginx daemons functions.
start() {
if [ -e $nginx_pid ];then
   echo "nginx already running...."
   exit 1
fi
   echo -n $"Starting $prog: "
   daemon $nginxd -c ${nginx_config}
   RETVAL=$?
   echo
   [ $RETVAL = 0 ] && touch /var/lock/subsys/nginx
   return $RETVAL
}
# Stop nginx daemons functions.
stop() {
        echo -n $"Stopping $prog: "
        killproc $nginxd
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx /usr/local/webserver/nginx/logs/nginx.pid
}

reload() {
    echo -n $"Reloading $prog: "
    #kill -HUP `cat ${nginx_pid}`
    killproc $nginxd -HUP
    RETVAL=$?
    echo
}
# See how we were called.
case "$1" in
start)
        start
        ;;
stop)
        stop
        ;;
reload)
        reload
        ;;
restart)
        stop
        start
        ;;
status)
        status $prog
        RETVAL=$?
        ;;
*)
        echo $"Usage: $prog {start|stop|restart|reload|status|help}"
        exit 1
esac
exit $RETVAL

4. 设置开机启动

chkconfig nginxd on

II、设置mysql开机启动

将mysql安装目录下 support-files目录下的mysql.server文件拷贝到/etc/init.d/目录下并改名为mysqld,并更改权限

chmod 775 /etc/init.d/mysqld

设置开机启动

chkconfig mysqld on

III、php-fpm开机启动

1. 在/etc/init.d/目录下创建脚本

vim /etc/init.d/php-fpm

2. 更改脚本权限

chmod 775 /etc/init.d/php-fpm

3. 编写脚本内容

#!/bin/sh
#
# php-fpm - this script starts and stops the php-fpm daemin
#
# chkconfig: - 85 15
# processname: php-fpm
# config:      /usr/local/php/etc/php-fpm.conf

set -e

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="php-fpm daemon"
NAME=php-fpm
DAEMON=/usr/local/php/sbin/$NAME     //这里设成自己的目录
CONFIGFILE=/usr/local/php/etc/php-fpm.conf   //这里设成自己的目录
PIDFILE=/usr/local/php/var/run/$NAME.pid   //这里设成自己的目录
SCRIPTNAME=/etc/init.d/$NAME   //这里设成自己的目录

# If the daemon file is not found, terminate the script.
test -x $DAEMON || exit 0

d_start(){
    $DAEMON -y $CONFIGFILE || echo -n " already running"
}

d_stop(){
    kill -QUIT `cat $PIDFILE` || echo -n " no running"
}

d_reload(){
    kill -HUP `cat $PIDFILE` || echo -n " could not reload"
}

case "$1" in
    start)
        echo -n "Starting $DESC: $NAME"
        d_start
        echo "."
        ;;
    stop)
        echo -n "Stopping $DESC: $NAME"
        d_stop
        echo "."
        ;;
    reload)
        echo -n "Reloading $DESC configuration..."
        d_reload
        echo "Reloaded."
        ;;
    restart)
        echo -n "Restarting $DESC: $NAME"
        d_stop
        # Sleep for two seconds before starting again, this should give the nginx daemon some time to perform a graceful stop
        sleep 2
        d_start
        echo "."
        ;;
    *)
        echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload)" >&2
        exit 3
        ;;
esac
exit 0

4. 设置开机启动

chkconfig php-fpm on

Ⅳ、redis 开机启动

1. 在/etc/init.d/目录下创建脚本

vim /etc/init.d/redis

2. 更改脚本权限

chmod 775 /etc/init.d/redis

3. 编写脚本内容

###########################
PATH=/usr/local/bin:/sbin:/usr/bin:/bin

REDISPORT=6379
EXEC=/usr/local/bin/redis-server
REDIS_CLI=/usr/local/bin/redis-cli

PIDFILE=/var/run/redis.pid
CONF="/etc/redis.conf"

case "$1" in
    start)
        if [ -f $PIDFILE ]
        then
                echo "$PIDFILE exists, process is already running or crashed"
        else
                echo "Starting Redis server..."
                $EXEC $CONF
        fi
        if [ "$?"="0" ]
        then
              echo "Redis is running..."
        fi
        ;;
    stop)
        if [ ! -f $PIDFILE ]
        then
                echo "$PIDFILE does not exist, process is not running"
        else
                PID=$(cat $PIDFILE)
                echo "Stopping ..."
                $REDIS_CLI -p $REDISPORT SHUTDOWN
                while [ -x ${PIDFILE} ]
               do
                    echo "Waiting for Redis to shutdown ..."
                    sleep 1
                done
                echo "Redis stopped"
        fi
        ;;
   restart|force-reload)
        ${0} stop
        ${0} start
        ;;
  *)
    echo "Usage: /etc/init.d/redis {start|stop|restart|force-reload}" >&2
        exit 1
esac
##############################

4. 设置开机启动

chkconfig redis on

至此,大功告成。

可以用命令 chkconfig 查看开机启动服务列表

chkconfig --list

附录:

1、nigx重启错误

bind() to 0.0.0.0:80 failed (98: Address already in use)

这个是nginx重启是 经常遇到的。 网上找了很多信息 都是没有啥用。说的乱七八糟的。 发现原来是nginx重复重启。自己占用了端口。 解决方法

killall -9 nginx

杀掉nginx 进程 然后重启就行了。

service nginx restart

2、php-fpm 启动 关闭

php-fpm 不再支持 php-fpm 补丁具有的 /usr/local/php/sbin/php-fpm (start|stop|reload)等命令,需要使用信号控制:

master 进程可以理解以下信号

  • SIGINT, SIGTERM 立刻终止
  • SIGQUIT 平滑终止
  • SIGUSR1 重新打开日志文件
  • SIGUSR2 平滑重载所有worker进程并重新载入配置和二进制模块

示例:

php-fpm 关闭:

kill -SIGINT `cat /usr/local/php/var/run/php-fpm.pid`

php-fpm 重启:

kill -SIGUSR2 `cat /usr/local/php/var/run/php-fpm.pid`

其次配置文件不再使用的xml 格式,改为了INI,但是配置参数几乎和以前一样,可参照xml格式的格式配置。

3、nginx 启动 关闭

  • nginx的启动 (nginx.conf文件基本上位于nginx主目录中的conf目录中)
nginx -c nginx.conf
  • nginx的停止 (nginx.pid文件基本上位于nginx主目录中的logs目录中)
ps -ef | grep nginx

可发现数个nginx进程,其中标有master的为主进程,其它为子进程, 停止nginx主要就是对主进程进行信号控制.

从容停止

kill -QUIT `cat nginx.pid`

快速停止

kill -TERM `cat nginx.pid`

or

kill -INT `cat nginx.pid`

强制停止

kill -9 `cat nginx.pid`

nginx的平滑重启

首先要验证新的配置文件是否正确:

nginx -t -c nginx.conf

成功后向主进程发送HUP信号即可: [/shell]kill -HUP cat nginx.pid[/shell]

4、nginx 平滑升级

  1. 备份好旧的可执行文件,使用新版本替换旧版本

  2. kill -USR2 旧版本的主进程PID 进行平滑升级, 此时新老版本共存

  3. kill -WINCH 旧版本的主进程PID 逐步关闭旧主进程的工作进程

  4. 当旧主进程产生的工作进程全部关闭后, 可以决定是否使用新版本还是旧版本.(需要使用kill命令来杀死新或旧主进程)

#!/bin/sh
BASE_DIR='/usr/local/'
${BASE_DIR}nginx/sbin/nginx -t -c ${BASE_DIR}nginx/conf/nginx.conf >& ${BASE_DIR}nginx/logs/nginx.start
info=`cat ${BASE_DIR}nginx/logs/nginx.start`
if [ `echo $info | grep -c "syntax is ok" ` -eq 1 ]; then
if [ `ps aux|grep "nginx"|grep -c "master"` == 1 ]; then
kill -HUP `cat ${BASE_DIR}nginx/logs/nginx.pid`
echo "ok"
else
killall -9 nginx
sleep 1
${BASE_DIR}nginx/sbin/nginx
fi
else
echo "######## error: ########"
cat ${BASE_DIR}nginx/logs/nginx.start
fi

5、CentOS修改系统环境变量

我这里拿php作为一个例子,我的php安装在/usr/local/webserver/php下,没有把php加入环境变量时,你在命令行执行

# 查看当前php的版本信息
[root@CentOS ~]# php -v

会提示你此命令不存在。

下面详细说说linux下修改环境变量的方法

方法一:

在/etc/profile文件中添加变量【对所有用户生效(永久的)】
用VI在文件/etc/profile文件中增加变量,该变量将会对Linux下所有用户有效,并且是“永久的”。

[root@CentOS ~]# vim /etc/profile

在文件末尾加上如下两行代码

PATH=/usr/local/webserver/php/bin:$PATH
export PATH

如:

# /etc/profile

# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc

# It's NOT a good idea to change this file unless you know what you
# are doing. It's much better to create a custom.sh shell script in
# /etc/profile.d/ to make custom changes to your environment, as this
# will prevent the need for merging in future updates.

pathmunge () {
    case ":${PATH}:" in
        *:"$1":*)
            ;;
        *)
            if [ "$2" = "after" ] ; then
                PATH=$PATH:$1
            else
                PATH=$1:$PATH
            fi
    esac
}

if [ -x /usr/bin/id ]; then
    if [ -z "$EUID" ]; then
        # ksh workaround
        EUID=`id -u`
        UID=`id -ru`
    fi
    USER="`id -un`"
    LOGNAME=$USER
    MAIL="/var/spool/mail/$USER"
fi

# Path manipulation
if [ "$EUID" = "0" ]; then
    pathmunge /sbin
    pathmunge /usr/sbin
    pathmunge /usr/local/sbin
else
    pathmunge /usr/local/sbin after
    pathmunge /usr/sbin after
    pathmunge /sbin after
fi

HOSTNAME=`/bin/hostname 2>/dev/null`
HISTSIZE=1000
if [ "$HISTCONTROL" = "ignorespace" ] ; then
    export HISTCONTROL=ignoreboth
else
    export HISTCONTROL=ignoredups
fi

export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL

# By default, we want umask to get set. This sets it for login shell
# Current threshold for system reserved uid/gids is 200
# You could check uidgid reservation validity in
# /usr/share/doc/setup-*/uidgid file
if [ $UID -gt 199 ] && [ "`id -gn`" = "`id -un`" ]; then
    umask 002
else
    umask 022
fi

for i in /etc/profile.d/*.sh ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then
            . "$i"
        else
            . "$i" >/dev/null 2>&1
        fi
    fi
done

unset i
unset pathmunge

PATH=/usr/local/webserver/php/bin:$PATH
export PATH

要是刚才的修改马上生效,需要执行以下代码

[root@CentOS ~]# source /etc/profile

这时再查看系统环境变量,就能看见刚才加的东西已经生效了

[root@CentOS ~]# echo $PATH
/usr/local/webserver/php/bin:/usr/lib/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin

现在就能直接使用php命令了(而不是像之前写很长一串/usr/local/webserver/php/bin/php -v),例如查看当前php的版本

[root@CentOS ~]# php -v
PHP 5.3.8 (cli) (built: Jun 27 2012 14:28:20)
Copyright (c) 1997-2011 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend Technologies

方法二:

在用户目录下的.bash_profile文件中增加变量【对单一用户生效(永久的)】
用VI在用户目录下的.bash_profile文件中增加变量,改变量仅会对当前用户有效,并且是“永久的”。具体操作和方法1一样,这里就不在列举代码了。

方法三:

直接运行export命令定义变量【只对当前shell(BASH)有效(临时的)】

在shell的命令行下直接使用[export变量名=变量值]定义变量,该变量只在当前的shell(BASH)或其子shell(BASH)下是有效的,shell关闭了,变量也就失效了,再打开新shell时就没有这个变量,需要使用的话还需要重新定义。例如

export PATH=/usr/local/webserver/php/bin:$PATH

Linux下安装配置OpenResty,并测试在Nginx中使用Lua编程

一、简介

OpenResty,也被称为“ngx_openresty”,是一个以Nginx为核心同时包含很多第三方模块的Web应用服务器。借助于Nginx的事件驱动模型和非阻塞IO,可以实现高性能的Web应用程序。 OpenResty不是Nginx的分支,它只是一个软件包。主要有章亦春维护。

OpenResty默认集成了Lua开发环境,而且提供了大量组件如Mysql、Redis、Memcached等,使得在Nginx上开发Web应用更方便简单。

二、安装OpenResty

[root@hbase31 src]# wget https://openresty.org/download/openresty-1.11.2.5.tar.gz
[root@hbase31 src]# tar -zxvf openresty-1.13.6.1.tar.gz
[root@hbase31 openresty-1.13.6.1]# ./configure --prefix=/usr/local/openresty --user=www --group=www --with-http_stub_status_module --with-http_ssl_module --with-openssl=/usr/local/ssl --with-pcre=/usr/local/src/pcre-8.38 --add-module=/usr/local/src/ngx_cache_purge-2.3 --with-http_gzip_static_module --with-luajit
[root@hbase31 openresty-1.13.6.1]# make && make install

注:关于这里的编译参数可以认为是在Nginx的编译参数的基础上添加了其他组件的参数。如需查看更多参数可以使用以下命令:

[root@hbase31 openresty-1.13.6.1]# ./configure --help

配置nginx的启动脚本:

[root@hbase31 openresty-1.13.6.1]# vim /etc/init.d/nginx

添加如下内容:

#!/bin/bash
# nginx Startup script for the Nginx HTTP Server
# it is v.1.3.0 version.
# chkconfig: - 85 15
# description: Nginx is a high-performance web and proxy server.
#              It has a lot of features, but it's not for everyone.
# processname: nginx
# pidfile: /var/run/nginx.pid
# config: /usr/local/openresty/nginx/conf/nginx.conf
nginxd=/usr/local/openresty/nginx/sbin/nginx
nginx_config=/usr/local/openresty/nginx/conf/nginx.conf
nginx_pid=/usr/local/openresty/nginx/logs/nginx.pid
RETVAL=0
prog="nginx"
# Source function library.
.  /etc/rc.d/init.d/functions
# Source networking configuration.
.  /etc/sysconfig/network
# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0
[ -x $nginxd ] || exit 0
# Start nginx daemons functions.
start() {
if [ -e $nginx_pid ];then
   echo "nginx already running...."
   exit 1
fi
   echo -n $"Starting $prog: "
   daemon $nginxd -c ${nginx_config}
   RETVAL=$?
   echo
   [ $RETVAL = 0 ] && touch /var/lock/subsys/nginx
   return $RETVAL
}
# Stop nginx daemons functions.
stop() {
        echo -n $"Stopping $prog: "
        killproc $nginxd
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx $nginx_pid
}
reload() {
    echo -n $"Reloading $prog: "
    #kill -HUP `cat ${nginx_pid}`
    killproc $nginxd -HUP
    RETVAL=$?
    echo
}
# See how we were called.
case "$1" in
start)
        start
        ;;
stop)
        stop
        ;;
reload)
        reload
        ;;
restart)
        stop
        start
        ;;

status)
        status $prog
        RETVAL=$?
        ;;
*)
        echo $"Usage: $prog {start|stop|restart|reload|status|help}"
        exit 1
esac
exit $RETVAL

添加可执行权限:

[root@hbase31 openresty-1.13.6.1]# chmod a+x /etc/init.d/nginx

启动nginx:

[root@hbase31 openresty-1.13.6.1]# service nginx start

三、在Nginx中使用Lua脚本

[root@hbase31 vhost]# cd /usr/local/openresty/nginx/conf
[root@hbase31 conf]# mkdir lua vhost

(1)测试在Nginx中使用Lua脚本

[root@hbase31 nginx]# vim /usr/local/openresty/nginx/conf/vhost/lua.conf

其内容如下:

server {
    server_name localhost;
    listen 3000;
    index index.html index.htm index.jsp;

    location / {
        root /usr/local/openresty/nginx/html;
    }

    location /lua {
        default_type text/plain;
        content_by_lua 'ngx.say("hello,lua!")';
    } 

    limit_conn perip 1000;
    access_log logs/access_rua.log;
}

测试是否可以访问:

[root@hbase31 nginx]# service nginx reload

然后访问:http://192.168.1.31:3000/lua

如果输出以下内容则证明在Nginx中可以执行Lua脚本:

hello,lua!

(2)在Nginx中使用Lua脚本访问Redis

i)连接Redis集群,然后添加测试参数:

192.168.1.30:7000> set '123' '456'

ii)添加连接Redis的Lua脚本:

[root@hbase31 nginx]# vim /usr/local/openresty/nginx/conf/lua/redis.lua

其内容如下:

local redis = require "resty.redis"
local conn = redis.new()
conn.connect(conn, '192.168.1.30', '7000')
local res = conn:get("123")
if res==ngx.null then
    ngx.say("redis集群中不存在KEY——'123'")
    return
end
ngx.say(res)

iii)在上面的lua.conf配置文件中添加以下location:

    location /lua_redis {
        default_type text/plain;
        content_by_lua_file /usr/local/openresty/nginx/conf/lua/redis.lua;
    }
1
2
3
4
    location /lua_redis {
        default_type text/plain;
        content_by_lua_file /usr/local/openresty/nginx/conf/lua/redis.lua;
    }

iv)测试是否可以访问:

[root@hbase31 nginx]# service nginx reload

然后访问:http://192.168.1.31:3000/lua_redis

如果输出以下内容则证明可以访问redis:

456

如何隐藏Linux中的Nginx服务器版本

在这篇简短的文章中,我们将向您展示如何在错误页面和Linux的“ 服务器HTTP ”响应头字段中隐藏Nginx服务器版本。 这是保护您的Nginx HTTP和代理服务器的主要推荐实践之一。

另请参阅 : 如何隐藏Apache版本号和其他敏感信息

本指南假设您已经在您的系统上安装了Nginx,或者根据您的Linux发行版遵循以下任何教程来设置完整的LEMP:

如何在Debian 9 Stretch上安装LEMP(Linux,Nginx,MariaDB,PHP-FPM)
如何在FreeBSD上安装Nginx,MariaDB和PHP(FEMP)
如何在16.10 / 16.04安装Nginx,MariaDB 10,PHP 7(LEMP)
在RHEL / CentOS 7/6和Fedora上安装最新的Nginx 1.10.1,MariaDB 10和PHP 5.5 / 5.6
“ server_tokens ”指令负责在错误页面和“服务器”HTTP响应头字段中显示Nginx版本号和操作系统,如下图所示。

Nginx版本号

要禁用此功能,您需要关闭/etc/nginx/nginx.conf配置文件中的server_tokens指令。

# vi /etc/nginx/nginx.conf
OR
$ sudo nano /etc/nginx/nginx.conf

在下面的屏幕截图中将下面的行添加到http上下文中作为shwon。

server_tokens off;

linux 配置nfs挂载共享目录

第一步:安装nfs;

第二步:启动nfs;

service nfs start

第三步:编辑/etc/exports文件;

加入:/xxxdir
xxx.xxx.xxx.xxx(rw,sync,no_root_squash),xxx.xxx.xxx.xxx是要挂载的IP

例如:

/temp      192.168.9.19(rw,sync,no_root_squash)
/共享目录        地址      (权限)

地址可以使用完整IP或网段,也可以地址可以使用主机名,DNS解析的和本地/etc/hosts解析的都行

权限有:  
rw:read-write,可读写;    注意,仅仅这里设置成读写客户端还是不能正常写入,还要正确地设置共享目录的权限,参考问题7  
ro:read-only,只读;  
sync:文件同时写入硬盘和内存;  
async:文件暂存于内存,而不是直接写入内存;  
no_root_squash:NFS客户端连接服务端时如果使用的是root的话,那么对服务端分享的目录来说,也拥有root权限。显然开启这项是不安全的。  
root_squash:NFS客户端连接服务端时如果使用的是root的话,那么对服务端分享的目录来说,拥有匿名用户权限,通常他将使用nobody或nfsnobody身份;  
all_squash:不论NFS客户端连接服务端时使用什么用户,对服务端分享的目录来说都是拥有匿名用户权限;  
anonuid:匿名用户的UID值,通常是nobody或nfsnobody,可以在此处自行设定;  
anongid:匿名用户的GID值。 

第四步:重启nfs服务

service nfs restart

不影响其他挂载目录情况下加载应用exports修改:

exportfs -r
或者
service nfs reload

第五步:在挂载机上(上面例子中192.168.9.19)新建目录,比如/itemp,并更改权限

chmod -R 777 itemp

最后挂载:

mount -t nfs 共享主机IP:/temp /itemp

Linux中利用shell脚本定时检测mysql状态,实现自动重启

问题简介

未分类

最近几个月网站服务器老是半夜挂掉,罪魁祸首就是 mysql 自动停止导致的,那就头痛医头,想办法让Mysql 自动启动起来。要解决这个mysql无规律自动停掉的问题,首先给服务器加个定时执行任务,每分钟去检测一下数据库服务的运行状态,要是down 掉了,就立马启动起来。

处理步骤

第一步,添加定时任务,使用crontab。

crontab -e
*/1 * * * * /目录/文件名.sh

#表示每分钟执行一次 sh 文件

第二步,编写shell执行文件,代码如下:

#!/bin/bash
pgrep -x mysqld &> /dev/null
if [ $? -ne 0 ]
then
echo “At time: `date` :MySQL is stop .”>> /日志路径
/etc/init.d/mysqld start
else
echo “MySQL server is running .”
fi

这里要注意,不能用

service mysqld/mysql start

命令来启动,会导致mysql启动不了,应使用绝对路径,

/etc/init.d/mysqld start

来启动。

另外,也可以不写入日志。删掉>> /日志路径即可。

完成。

就是这么简单。如发现这样操作了,还没有得到期望的结果,可排查crontab是否执行了相应的任务,脚本权限是否够,脚本内部命令或格式是否正确等方面。

如写入

*/1 * * * * echo “test” >> /var/log/test

检测cron是否正确执行。

再看看crontab的执行历史记录:

cd /var/log
tail -100 cron

若权限不够,则加上权限。

chmod 777 ./shell文件.sh