`
fantaxy025025
  • 浏览: 1247767 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类

ubuntu开机和登陆后自动运行哪些脚本程序

 
阅读更多

 

1.开机启动时自动运行程序

Linux 加载后, 它将初始化硬件和设备驱动, 然后运行第一个进程init。init根据配置文件继续引导过程,启动其它进程。通常情况下,修改放置在 /etc/rc或 /etc/rc.d 或 /etc/rc?.d 目录下的脚本文件,可以使init自动启动其它程序。例如:编辑 /etc/rc.d/rc.local 文件(该文件通常是系统最后启动的脚本),在文件最末加上一行“xinit”或“startx”,可以在开机启动后直接进入X-Window。

 

开机后还要自动运行很多服务,如mysql,memcache等。

 

2.登录时自动运行程序

用户登录时,bash首先自动执行系统管理员建立的全局登录script :/ect/profile。然后bash在用户起始目录下按顺序查找三个特殊文件中的一个:/.bash_profile、/.bash_login、 /.profile,但只执行最先找到的一个。
因此,只需根据实际需要在上述文件中加入命令就可以实现用户登录时自动运行某些程序(类似于DOS下的Autoexec.bat)。

 

注意不是自动运行.bashrc脚本,而是.profile脚本。

可以看看源码.profile:

# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
,.. "$HOME/.bashrc"
    fi  
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

 可以看出,我们平时使用的.bashrc文件,仅仅是被.profile脚本加载的。

所以很多同学默认是zsh会导致纯粹按照某些文章指示编写.bashrc脚本的环境变量不起作用,比如使用rvm的。

 

3.退出登录时自动运行程序

退出登录时,bash自动执行个人的退出登录脚本/.bash_logout。例如,在/.bash_logout中加入命令“tar -cvzf c.source.tgz *.c”,则在每次退出登录时自动执行 “tar” 命令备份 *.c 文件。

4.定期自动运行程序

Linux有一个称为crond的守护程序,主要功能是周期性地检查 /var/spool/cron目录下的一组命令文件的内容,并在设定的时间执行这些文件中的命令。用户可以通过crontab 命令来建立、修改、删除这些命令文件。

例如,建立文件crondFile,内容为“00 9 23 Jan * HappyBirthday”,运行“crontab cronFile”命令后,每当元月23日上午9:00系统自动执行“HappyBirthday”的程序(“*”表示不管当天是星期几)。

 

 

因为.bashrc或者说.profile文件是在登录时才执行的,如果不登陆能执行么,或者说如果要运行服务怎么办,此时并没有某个用户登陆,也就麽有相应的环境变量了。

比如启动rails的服务的www用户。

 

使用sudo命令的参数-i

查看manue:

       -i [command]

                   The -i (simulate initial login) option runs the shell specified by the password database entry of the target user as a loginshell.  This means that login-specific resource files such as .profile or .login will be read by the shell.  If a command isspecified, it is passed to the shell for execution via the shell's -c option.  If no command is specified, an interactive shellis executed.  sudo attempts to change to that user's home directory before running the shell.  The security policy shall initialize the environment to a minimal set of variables, similar to what is present when a user logs in.  The Command Environment section in the sudoers(5) manual documents how the -i option affects the environment in which a command is run when the sudoers policy is in use.

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics