date
int64
1,220B
1,719B
question_description
stringlengths
28
29.9k
accepted_answer
stringlengths
12
26.4k
question_title
stringlengths
14
159
1,667,594,652,000
A domain name is an abstraction for an IP address. Regardless of which computer is at that IP, the domain name should point there. So why then do we associate a domain name with a computer using the /etc/{hosts,hostname} and/or systemd's hostnamectl? I'm definitely clueless, but this just seems wrong to me. I'm setting up my first server at home that will be publicly accessible, using a dynamic DNS for the domain name, and so came across this hosts/hostname question. I'm not the only one to ask it, but that person didn't get an answer.
In /etc/hostname (see man 5 hostname) you can and should set the local hostname of your server. This name may be used from software running on this server. This is just a string, which is not visible outside of the server. In contrast, the file /etc/hosts is used to resolve computer names to IP addresses. You can think of this as a poor-mans DNS server. In the old times, before the Domain Name System was developed, large host files were actually sent on the computers on the Internet to map a uniform network with names. Usually there is no need to add entries here, if you have a running DNS server and no local network with more than one server. In order not to be dependent on a name server, you can enter your own servers and their IP addresses in /etc/hosts. However, you should note that with at more servers and changing address ranges, it becomes tedious to maintain this file.
Domain Name as IP Abstraction vs. Domain Name as Name of Server - /etc/host{s,name} - Why?
1,667,594,652,000
I use the following syntax in order to find the domain name on a Linux machine: hostname | sed s'/\./ /g' | awk '{print $2}' hostname master02.sys65.com hostname | sed s'/\./ /g' | awk '{print $2}' sys65 but I think this approach is not very elegant. I would like to see other ways to find the domain name (without the final .com).
You should use hostname -d for this. To drop the last part of the domain, there any many different techniques; for example hostname -d | sed -E 's/\.[^.]+$//'
What is the best approach to find a system's domain name?
1,667,594,652,000
On my work's network, my new debian headless VM is not visible via its hostname. I'm using: Debian Jessie Virtualbox bridged adapter I can see other VMs on my machine from the headless VM, and I can see other machines on the network from the headless VM (that is, ping machine works for both cases). I can also ping the host machine. I tried installing acahi-daemon and avahi-discover, as per this thread with no success. Additionally, I edited dhclient.conf to have the line send host-name "Peridot"; (Peridot being the VM's hostname). Specifically, I'm hosting an instance of haste-server on the machine, which I can access via browser by the machine's IP but not by it's hostname (which is what I'd like). I cannot ping it from any other machine on the network by name, but it can be reached via its IP. Any help appreciated
Your Windows machines can use NetBIOS Name Resolution to tell each other about themselves. This is Microsoft specific protocol and doesn't work with Linux/Unix machines, which use a static file (/etc/hosts) or the Domain Name Service (DNS) for name resolution. Your Windows machines will not recognise the AVAHI service without installing one on each machine (I believe Apple provide one). You have a few options: Edit the hosts file mentioned above on all computers (it's in C:\Windows\System32\drivers\etc on Windows and in /etc/ on Linux). As a minimum, you'll have to add all Linux machines/VMs to it. Run a DNS server on one of your machines. Install samba on your Debian VM. This is a service that allows a Linux machine to share it's files with Windows client. It also happens to announce the host using the NetBIOS Name Resolution service so your Windows machines will be able to see the Linux VM by name. As @JoelDavies comments, this will be one way only. It won't allow the Debian VM to access all other Windows machines by name, but will allow all Windows machines to access the Debian by name.
Can ping Debian VM via IP but not via hostname
1,667,594,652,000
Unfortunatelly I made mistake somewhere but can't get where. I had issues with ssh and github, tried different things and they didn't work. Later I decided .. i think.. moved file i balieve it was home/username/known.hosts or smth like that. Additonally I deleted everything from folder, where id_25519 and id_25519.pub files (maybe they are related to github, i don't know). And somewhere in between or afteer all. I could not provide my password in terminal. I 200% sure it's correct, no caps/num/ other things used. and now i can't log in to my linux mint cinamon 20. I will really appreciate any help how can I recover my laptop. It starts, but requires pass. And I can't understad how coudl it change ......
It's unlikely modifying anything in your home directory will have reset your password. On most distributions it's stored in /etc/shadow by default. To get to a recovery console, the most easy thing to try is to change the init kernel parameter on boot. Assuming you are booting with grub: switch on your computer At the boot menu press e to edit the boot entry You might be asked for your grub password if you have one set Modify the line starting linux to add init=/bin/bash at the end Press f10 to boot This should give you a root command line with / mounted readonly. To make it read-write remount it: mount -o remount,rw / You should be able to reset your password with: passwd <username> And finally reboot with: reboot
password to linux changed after deleting/manipulation with ssh
1,667,594,652,000
I just installed EndeavourOS. I set my hostname using the command sudo hostnamectl set-hostname shuttle. When I try to ping shuttle from my other machines it is not able to resolve the IP address. I have another machine with Kubuntu installed, and I am able to ping the Kubuntu box. So it means my router isn't the problem. Is there something I need to enable to allow the EndeavourOS to send the hostname to my router?
The mere fact of setting the hostname of your system alone is not enough to make it known to other systems in your network. Even if your router actually has a DNS service that can be aware of hosts on your local network (and this is not certain by any means), your DHCP client must 1.) actually pass the locally-configured hostname to the DHCP server in the router, and 2.) actually request for the DHCP server to perform the DNS update. Both of these things are configurable, and not necessarily enabled by default. And often the router's "DNS server" is essentially just a proxy for the ISP's DNS service, which does not care about hosts in your local network at all. If the hostname resolution in your local network has "just worked" before, it is much more likely that it's been using an alternative mechanism instead of plain DNS. For Linux and macOS systems, this mechanism is multicast DNS (mDNS), a part of Avahi/Bonjour/Zeroconf services. Windows previously used NetBIOS (which is now very much deprecated after the WannaCry worm exploited an unfixable design flaw in it) and LLMNR (another link-local hostname resolution protocol), but is apparently now adding mDNS support too. In Linux, mDNS works by having the avahi-daemon announce the identity of your system periodically to the local network segment, and answer with the relevant information if anyone on the local system sends out a query for this system's name. This takes care of other hosts being able to find this one; the other part is a name server switch module that allows the Linux system to seamlessly use mDNS in addition to regular DNS. In Debian and related distributions this comes packaged as libnss-mdns; if the hosts: line of your /etc/nsswitch.conf file includes keywords like mdns, mdns4 or mdns6, it should be in use. There are also keywords mdns4_minimal, mdns_minimal, which will enable mDNS only for hostnames qualified with the special domain name .local. So trying ping shuttle.local may have different results from just ping shuttle. Alternatively, if you use systemd-resolved as your DNS resolver (indicated by the use of the keyword resolve instead of dns in your /etc/nsswitch.conf, or the presence of nameserver 127.0.0.53 in /etc/resolv.conf), it can use both mDNS and LLMNR in addition to classic DNS to resolve the names of other hosts. Check the output of resolvectl to see if mDNS is actually enabled or not. If your EndeavourOS has either the mDNS resolver component or systemd-resolved installed and configured, but no avahi-daemon to announce its identity to other hosts, that would explain why EndeavourOS can resolve the Kubuntu system, but not vice versa. Kubuntu includes avahi-daemon in its default configuration; I'm not very familiar with EndeavourOS.
Can't ping or DNS resolve the EndeavourOS machine
1,667,594,652,000
I've been looking to a tutorial on how to customize my terminal. When I try to customize the PS1 into something like PS1="\u@\h \W -> " export PS1; After I source the file in the terminal, instead of getting the username@host directory I get \u@\h \W -> What I have so far in my .bash_profile and .bashrc files is: .bash_profile if [ -s ~/.bashrc ]; then source ~/.bashrc; fi .bashrc PS1="\u@\h \W -> " export PS1; Any help would be highly appreciated, thanks!
What output do you get for echo $0 ? The output is -zsh Which seems to mean you're running Zsh, not Bash. Zsh doesn't support Bash's prompt expansions, but has a system of its own. See: http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html Try to put something like this in .zshrc: PS1='%n@%M %~ -> ' You could verify which login shell you have by peeking at /etc/passwd, or running getent passwd $USER (should work on Linuxes). The last field is the shell. If you want to run Bash as your login shell, chsh -s /bin/bash should work to change that.
Special characters don't work in bashrc
1,667,594,652,000
I'm used to debian/raspbian, setting the hostname for a computer is easy as: /etc/hostname: my-computer and /etc/hosts: 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters 127.0.1.1 my-computer After these changes and a restart, I can ssh [email protected] from any other machine on my local network. I am having a really hard time getting this behavior on a new gentoo system. I've tried a few other settings from 2-3 year old posts on the gentoo forums with no luck.
For ssh [email protected] to work, two things must be in place: my-computer must be running avahi-daemon or some other implementation of multicast DNS (mDNS for short). This will periodically announce the current hostname & IP of the computer to the local network, and will respond with that information if some other device in the local network asks for it. The announced name will be of the form <short hostname>.local. the computer with the SSH client must include mdns, mdns4_minimal or similar mDNS hostname resolution module listed on the hosts: line of /etc/nsswitch.conf. This makes the glibc's hostname resolution function actually use mDNS as one possible source of hostname/IP information. mDNS is compatible with the Apple's Bonjour system, and apparently Microsoft may have some support for it too - although modern versions of Windows seem to prefer WS-Discovery, another multicast-based protocol, for a similar purpose. The top-level DNS domain .local is now reserved for mDNS use, so it should not be used for regular private DNS domains any more. However, for the sake of backwards compatibility, there is some support to allow names with three or more parts (e.g. <hostname>.something.local) to still work with regular DNS; two-part names (<hostname>.local) will be resolved by mDNS on mDNS-aware systems.
Gentoo: how to set hostname for local network?
1,667,594,652,000
I have a Linux server # uname -a Linux site 3.12.39-47-default #1 SMP Thu Mar 26 13:21:16 UTC 2015 (a901594) x86_64 x86_64 x86_64 GNU/Linux # lsb_release -a LSB Version: n/a Distributor ID: SUSE LINUX Description: SUSE Linux Enterprise Server 12 Release: 12 Codename: 12 I had to change network settings. I've set one interface as DHCP in Gnome GUI. Since that moment I have a new problem: my server forgets its own host name every day. Its host name is "site", but when I check #hostname host Then I set #hostname site Then check #hostname site However, about in day later I check again #hostname host Why does it happen? /etc/hostname file contains: site /etc/hosts file contains: 127.0.0.1 localhost 127.0.1.1 site
Your DHCP client can be configured to override the hostname given to the machine by the DHCP server. Depending on what DHCP client you use, this may be done differently. dhclient may be configured with supersede host-name "site"; in /etc/dhclient.conf, for example. Unless you have very special requirements, I'd suggest you make the entry in /etc/hosts as 127.0.0.1 localhost site This says "localhost has IP address 127.0.0.1 and site is an alias for it".
My Linux server forgets its host name every day
1,667,594,652,000
I would like the hostname command to show the fqdn by default on CentOS Linux. What must be done to get this behavior? I am not looking to alias hostname to 'hostname --fqdn' I am looking to modify the system in a way that the gethostbyname calls, or whatever is used to get hostname get the entire fqdn ala host.example.bar.
Add the FQDN hostname to /etc/sysconfig/network: HOSTNAME=host.example.bar After a system restart the hostname command (without any options) should display the FQDN. [user@host ~]# hostname host.example.bar This works on CentOS 5/6.
Get hostname to show fqdn without --fqdn
1,667,594,652,000
We have tried both the /etc/hosts and also /etc/sysconfig/network. Edited both files and service network restart. Yet the hostname is showing as localhost.localdomain. How to resolve on this? Googling almost all talking about the same method too.
From this answer : How to change the hostname of a RHEL-based distro? Have you tried running the command : hostname new_hostname where "new_hostname" would be value you are trying to set ?
Editing /etc/hosts and /etc/sysconfig/network doesn't chane the hostname [duplicate]
1,667,594,652,000
I want to set name to my localhost.for example I want mysite.com instead of localhost/mysite how to do that? I have searched but couldn't get a solution for Linux.
Find and change the following line in /etc/hosts: 127.0.0.1 localhost Change it to 127.0.0.1 localhost mysite.com This is client side. Your webserver may need be configured for name based vhosts.
How to set name to localhost in fedora15?
1,667,594,652,000
When trying to ssh from terminal into my raspberry pi using: ssh [email protected] the connection just hangs forever. When I ping [email protected], I get ping: cannot resolve [email protected]: Unknown host I can ping and ssh with the ip address just fine using: ssh [email protected] Not sure if I need to configure my laptop network settings (macOS) or the raspberry pi settings (Debian) to be able to connect via hostname.
When you give a host a hostname, only this host knows about it. Any other host doesn't know the hostname (and the IP address it corresponds to) at all. A little different are name services (like DNS, NIS, ...), which "distribute" this knowledge across a network. But for our purposes only the host himself knows its hostname. Having said this: you want to connect from a system (let us call it "yourpc") to another system ("pi"). For this to work "yourpc" has to know which IP address corresponds to this name "pi". In absence of any name service there is one way to enlighten "yourpc", which is: enter the hostname and its corresponding IP address to the file /etc/hosts. In fact this is the specific purpose of this file. A typical /etc/hosts file looks like this: # Place comments after octothorpe signs, like in shell scripts 10.1.1.1 host1 10.1.1.2 host2 10.1.1.3 host3 # an inline comment is also possible # you can also specify "aliases" - multiple names under which the host is also known 10.1.1.4 host4 myraspberrypi ... As an afterthought and thanks to a suggestion of @Archemar: User names are irrelevant on the IP level. At this level we deal only with hosts (or, rather, their interfaces), networks and similar entities. Users or their names never enter this picture at this level. Using the above example hosts-file the following are all equal: ssh [email protected] ssh someuser@host4 ssh someuser@myraspberrypi
Cannot ssh into a host using hostname.local
1,667,594,652,000
There are two different version of hostname on my system. This is a problem when trying to use wget against $HOSTNAME, which differs from what is expected. [user@box ~]# wget https://$HOSTNAME/login.php --2021-08-22 23:25:07-- https://superserver/login.php Resolving superserver (superserver)... 11.22.33.44 Connecting to superserver (superserver)|11.22.33.44|:443... connected. The certificate's owner does not match hostname ‘superserver’ [user@box ~]# echo $HOSTNAME superserver [user@box ~]# cat /proc/sys/kernel/hostname superserver.some.domain.com [user@box ~]# [user@box ~]# hostname superserver.some.domain.com [user@box ~]# How do I update my system such that $HOSTNAME reflects what is in /proc/sys/kernel/hostname, and what appears when I issue hostname? Or do I simply add a line in /etc/hosts?
hostnamectl set-hostname superserver.some.domain.com systemctl reboot now
$HOSTNAME mismatch
1,667,594,652,000
I SSH to my Raspberry Pi's wifi via ssh raspberrypi.local, simply done by adding the following code in a file named wpa_supplicant.conf ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev update_config=1 country=US network={ ssid="Welcome Home" psk="Thanhlich267" priority=1 } I am trying to learn to do the same thing with other Linux Embedded system (Google Coral Board, BeagleBone), but I did not know how to accomplish this. Can someone please advise me? Thanks,
wpa_supplicant.conf is just for configuring the WiFi network connectivity: it has nothing to do with making the .local hostname available. That part is done by the avahi-daemon service, which is enabled by default on RasPis. It uses the multicast DNS, or mDNS protocol to announce its name and IP to other systems on the same network segment (only). Normally, the default configuration of avahi-daemon should be enough to make the system findable in the network as <hostname>.local. Just make sure that the service is installed and started on your other embedded systems. Unfortunately, it looks like the Mendel Linux for Google Coral Board might be more stripped-down and so less user-friendly than the Raspbian that is commonly used on RasPis. BeagleBoards may have originally been delivered with the Ångstrom distribution but currently seem to have Debian-based images available for them - which are you using?
How to setup a .local Wifi hostname to SSH in a Linux system?
1,667,594,652,000
Assuming a Linux system has both hostname (/etc/hostname) and NetBIOS (/etc/samba/smb.config) enabled. My questions are: Are these 2 names synchronized somehow by default settings? (for example, after installing the samba, does the netbios name = something setting get changed in (/etc/samba/smb.config) to the same value of hostname (/etc/hostname)?) When the Linux system is pinged by its name, Would it be looked up by the name in its /etc/hostname or /etc/samba/smb.config?
'netbios name' is a name used by only some special programs. Your Linux system is in the network represented by all of its IP addresses (try ifconfig | grep inet), where 127.0.0.1 and ::1 are always your local machine. Pinging one of these IP addresses will reach you system. If you have a little more complex system, like DHCP via your internet gateway, which may give you a new address on every reboot, you should have a look at this service/router/name server, how it represents your system, what name it gave your system. In general have a look if /etc/resolv.conf shows you a 'nameserver' entry. That name server will be asked by your Linux system if you try to ping other systems by some name, and will decide under which names the other system is available. This may in some rare cases be the same as its Netbios name, if that system has one at all, but mostly it won't. Mostly the other systems name you try to reach, will include its entry of its /etc/hostname file, but may be changed by the name server, resulting in something like e.g. yourcomputer.fritz.box instead of yourcomputer, if you have a FritzBox to reach the internet, which then would often also be used as a name server. Still you can give all your local computers fixed IPs, and add their names (including an extra entry for the netbios name) to all /etc/hosts files (the most basic network name resolving system) on all computers in your network, so you can ping them by either 'normal' or netbios name, as both will only be an alias for the same fixed IP addresses.
Accessing a Linux system inside a network: is it via hostname or netbios name?
1,573,097,728,000
I have one box (Rasberry Pi, running rasberian) with a static IP. It's running in a network with a domainname, and I have several DNS-server set up. However, I can not get FQDN name to work on this box: sitron@pi:~ $ domainname (none) sitron@pi:~ $ dnsdomainname sitron@pi:~ $ hostname -f pi I believe I have set up DNS correctly: sitron@pi:~ $ hostname -I 192.168.10.9 2001:db8:abba::9 sitron@pi:~ $ cat /etc/resolv.conf domain example.org search example.org nameserver 2001:db8:abba::5 nameserver 192.168.10.5 sitron@pi:~ $ dig +short -x 192.168.10.9 @2001:db8:abba::5 pi.example.org. sitron@pi:~ $ dig +short -x 2001:db8:abba::9 @2001:db8:abba::5 pi.example.org. sitron@pi:~ $ dig +short -x 2001:db8:abba::9 @192.168.10.5 pi.example.org. sitron@pi:~ $ dig +short -x 192.168.10.9 @192.168.10.5 pi.example.org. My nsswitch.conf: # /etc/nsswitch.conf # # Example configuration of GNU Name Service Switch functionality. # If you have the `glibc-doc-reference' and `info' packages installed, try: # `info libc "Name Service Switch"' for information about this file. passwd: compat group: compat shadow: compat gshadow: files hosts: files mdns4_minimal dns networks: files protocols: db files services: db files ethers: db files rpc: db files netgroup: nis And /etc/hosts: 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters 127.0.1.1 pi What is the missing link?
I figured it out, and there is two solutions. I have tested both, on several different boxes. Solution A Verify that your resolv.conf contains the "domain"-keyword, like this: # Generated by resolvconf domain example.org nameserver 127.0.0.1 If you are using dhcpcd.conf to set a static IP like me, you have to specify this undocumented option: static domain_name=example.org Finally, you need to remove the line in /etc/hosts containing 127.0.1.1 <hostname>. That means my /etc/hosts now contains: 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters Solution B Add your FQDN to the 127.0.1.1 line in /etc/hosts, like this: 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters 127.0.1.1 pi.example.org pi However, this means I am overriding the DNS-server, something that is not ideal. That's why I prefer, and assume Solution A is better.
dnsdomainname and hostname -f does not return FQDN
1,573,097,728,000
I'm running Arch on my daily use laptop and I have two SSH terminals open up every time I login. I SSH into another Arch laptop, which is essentially a network connected hard drive in which I backup this laptop via Cron and rsync. The other device is Rasp Pi which is running OSMC and I do basic maintanance with the laptop. However the IPs keep changing all the time in my Wifi network so automatic SSH logins and Cron backups isn't working(since the command is username@ipaddress). Is there a way to assign static names to each Linux systems so the IP Address is not needed? Or am I completely misunderstanding how this thing works? Thanks.
If you have control over the WiFi you should have control over the DHCP server (in home networks most likely your WiFi router). I would then propose these possible solutions: Configure your DNS server (probably also on the WiFi router) to assign host names to the devices you want to reach. Then you can contact them by name rather than address. Configure your DHCP server so that the devices you want to reach always get assigned the same IP addresses. Most DHCP servers should be able to do so. The server identifies them using their MAC addresses. Have a look which address range is used by your DHCP server to assign addresses to devices. This could probably be something like 192.168.0.100 to 192.168.0.200 (for IPv4). Then assign some static addresses not in that range manually on the devices you want to read. OSMC is Debian-based, so you would most do it in /etc/network/interfaces. For Arch Linux, the configuration is different.
SSH without knowing IP addresses
1,573,097,728,000
Good day to all. I'll give you an example, I tried it There are 2 entries for BalanceMember in /etc/hosts. Of course, don’t look at these virtual machines, it’s a black box. All requests return to 404 not found. ServerName service.test.com SSLProxyEngine on <Proxy "balancer://service"> BalancerMember https://service1.ng.com BalancerMember https://service2.ng.com </Proxy> ProxyPass "/" "balancer://service/" ProxyPassReverse "/" "balancer://service/" If I edit /etc/hosts and change the name from service1.ng.com to service.ng.com then change conf apache to this ServerName service.test.com SSLProxyEngine on <Proxy "balancer://service"> BalancerMember https://service.ng.com BalancerMember https://service2.ng.com </Proxy> ProxyPass "/" "balancer://service/" ProxyPassReverse "/" "balancer://service/" One request out of 2 will return 200 OK. Do you understand, right? But I can’t understand. What does the proxy send to one of the balancers, that everything works. Well, or after the balancer, I don’t know. Thank you in advance for your response.
<Location "/"> ProxyPass "https://service.ng.com/" ProxyPassReverse "https://service.ng.com/" AllowOverride None Order Deny,Allow Deny from All Allow from All </Location> This block solved my problem. Thank you.
ProxyPass return 404, but one name OK
1,573,097,728,000
I have copied my headless Ubuntu 22LTS server to a backup drive with dd, and I want to deploy it as a backup server with the same relevant settings. What is the proper way to change the hostname on the copied drive before booting it from the backup hardware? As the systems run headless, I cannot login to the console to set it interactively after booting it. I need to bring it on the network and login via ssh, but of course I need to avoid collision with the running server. In the past, I just modified /etc/hostname on the mounted drive, but with systemd things may work differently.
@Tom Yan: Thanks for the link. I have searched for my hostname in config files on my system and found some which are not covered by the 'hostname' command. The main files are /etc/hostname and /etc/hosts, but there may also be /etc/postfix/main.cf and /etc/mailname which require adaptation if postfix is configured. The hostname may also be set in the gcos field of /etc/passwd to make mails from root show as root@hostname. Thus, I think it is best to search for files containing the old hostname and adapt them manually if necessary to cover specific settings of a host.
Howto change linux hostname on mounted (copied) drive
1,573,097,728,000
I have a raspberry with a dnsmasq server installed (via NetworkManager). I need to be able to resolve *.raspberry.local on my local (private) network. Here is my config : In /etc/NetworkManager/NetworkManager.conf I've added dns=dnsmasq to [main] In /etc/NetworkManager/dnsmasq.d/local.conf I've added local=/raspberry.local/192.168.1.10 where 192.168.1.10 is my local (permanent) IP defined in my router's DHCP. In /etc/dnsmasq.conf, I have the following config (taken from here) : domain-needed bogus-priv filterwin2k localise-queries local=/lan/ domain=raspberry.lan address=/raspberry.lan/192.168.1.10 expand-hosts no-negcache resolv-file=/tmp/resolv.conf.auto listen-address=127.0.0.1 Also there is no need to add a leading dot or wildcard. In /etc/systemd/resolve.conf I've added DNS=127.0.0.1 80.10.246.1 81.253.149.9 Domains=raspberry.local Which is supposed to tell my system to take localhost DNS first (with *.raspberry.local) and then Orange's (French ISP) DNS servers. My problem is that, I can curl (and visit on :80) raspberry.local but not it's subdomains without adding them to /etc/hosts, and even when I add any.raspberry.local to /etc/hosts only my raspberry can curl it. Also, in my /etc/resolv.conf, there is no sign of above config, I have to manually add my DNS server: nameserver 127.0.0.1 # my server nameserver 127.0.0.53 options edns0 trust-ad search raspberry.local local (What is 127.0.0.53, ins't it supposed to be 127.0.0.1:53 ?) Am I doing something wrong here ? I'm sure my DHCP config is good in my router, and same for the above. System : Ubuntu 22.04LTS Raspberry pi 4
I fixed my problem using this dnsmasq config: domain-needed bogus-priv filterwin2k expand-hosts localise-queries domain=raspberry.lan local=/raspberry.lan/ address=/raspberry.lan/192.168.1.10 expand-hosts no-negcache resolv-file=/tmp/resolv.conf.auto listen-address=127.0.0.1,192.168.1.10 and by changing resolved config using this : DNS=192.168.1.10 FallbackDNS=192.168.1.1 Domains=raspberry.lan /etc/resolv.conf won't change because 127.0.0.53 will handle everything.
Cannot resolve local sub domain on network
1,573,097,728,000
I want to make it so that instead of a single hostname specified on the command line, it reads in a list of multiple target IP addresses from a file. #!/bin/bash - # bannergrab.sh function isportopen () { (( $# < 2 )) && return 1 # <1> local host port host=$1 port=$2 echo >/dev/null 2>&1 < /dev/tcp/${host}/${port} # <2> return $? } function cleanup () { rm -f "$SCRATCH" } ATHOST="$1" SCRATCH="$2" if [[ -z $2 ]] then if [[ -n $(type -p tempfile) ]] then SCRATCH=$(tempfile) else SCRATCH='scratch.file' fi fi trap cleanup EXIT # <3> touch "$SCRATCH" # <4> if isportopen $ATHOST 21 # FTP <5> then # i.e., ftp -n $ATHOST exec 3<>/dev/tcp/${ATHOST}/21 # <6> echo -e 'quit\r\n' >&3 # <7> cat <&3 >> "$SCRATCH" # <8> fi if isportopen $ATHOST 25 # SMTP then # i.e., telnet $ATHOST 25 exec 3<>/dev/tcp/${ATHOST}/25 echo -e 'quit\r\n' >&3 cat <&3 >> "$SCRATCH" fi if isportopen $ATHOST 80 # HTTP then curl -LIs "https://${ATHOST}" >> "$SCRATCH" # <9> fi cat "$SCRATCH" # <10> The file containing the list looks like it: 10.12.13.18 192.15.48.3 192.168.45.54 ... 192.114.78.227 But how and where do I put a command like set target file:/home/root/targets.txt. Or it needs to be done in another way?
You seem to want to have "$1" represent a file containing a list of targets, instead of being just 1 target. So you will need to englob the main part in a loop ATHOSTFILE="$1" SCRATCH="$2" for ATHOST in $( cat "$ATHOSTFILE" ); do ... # (the rest of the actions here) done Note that the $( cat "$ATHOSTFILE ) part will be replaced by the content of $ATHOSTFILE, and read "element by element", each element being splitted using $IFS (usually: any space(s) and tab(s) and newline(s) will act as separators). There are quite a few other things to say about the syntax, and structure, but this should lead you in the right direction.
Instead of a single hostname specified on the command line, it reads in a list of multiple target IP addresses from a file
1,573,097,728,000
This morning the connection and all the things were working fine, until I following some online tutorial, installed Postfix and changed /etc/hostname and /etc/hosts. Now ping to the local router: 198.168.3.1 is working fine, but not when I try to reach anywhere out of the firewall: ping 8.8.8.8 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. From 192.168.3.46 icmp_seq=1 Destination Host Unreachable ping 192.168.3.1 PING 192.168.3.1 (192.168.3.1) 56(84) bytes of data. 64 bytes from 192.168.3.1: icmp_seq=1 ttl=64 time=8.62 ms I uninstalled Postfix, changed /etc/hostname and /etc/hosts, but the problem remains. I will use example.com to cover the real domain. Here's my ifconfig for the instance: eno1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.3.46 netmask 255.255.255.0 broadcast 192.168.3.255 inet6 fe80::bacb:29ff:fea3:a598 prefixlen 64 scopeid 0x20<link> ether b8:cb:29:a3:a5:98 txqueuelen 1000 (Ethernet) RX packets 4377 bytes 708162 (708.1 KB) RX errors 0 dropped 28 overruns 0 frame 0 TX packets 875 bytes 62510 (62.5 KB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 device interrupt 17 Here's my /etc/netplan: # This is the network config written by 'subiquity' network: version: 2 renderer: networkd ethernets: eno1: addresses: [192.168.3.46/24] gateway4: 192.168.3.254 nameservers: addresses: [8.8.4.4,8.8.8.8] Here's the /etc/hosts: 127.0.0.1 localhost 127.0.0.1 example.com 127.0.1.1 www.example.com # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters Here's the /etc/hostname: example.com The server still takes request, but cannot send anything past the LAN: traceroute 8.8.8.8 traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 60 byte packets 1 example.com (192.168.3.46) 2325.811 ms 2325.800 ms 2325.793 ms I reset the Firewalls and did everything I can, someone please help...
All thanks to @icarus, just realize that the gateway and router should share the same address which handles all incoming and outgoing traffic. There were 2 routers working for a different purpose earlier, that's why the problem only occurred today because the other router's rule was changed.
Ubuntu Server: After Trying to Set Email Server Using Postfix, Ping 8.8.8.8 Only Gives Destination Host Unreachable
1,573,097,728,000
Let's say I want to run a script when the hostname is change on a machine with hostnamectl set-hostname NAME Is there a way to hook into this? How would I go about doing it?
It is possible. I don't have full instructions. (Feel free to post any script you write etc, and take due credit for it :-). hostnamectl / hostnamed does not run scripts. When you change the hostname using hostnamectl, hostnamed emits a dbus signal called PropertyChanged. You could hook up to the dbus signal, using something like dbus-monitor. https://askubuntu.com/questions/150790/how-do-i-run-a-script-on-a-dbus-signal The link above describes starting the dbus-monitor script when you log in to a graphical environment. It does this using an XDG autostart. If you want your dbus-monitor script to run without you logging in to a graphical environment, you could use a simple systemd service instead.
Is it possible to hook into hostnamectl?
1,573,097,728,000
I have created a shell script to connect to a list of servers using sshpass and run a list of about 30 commands. An extract of the script is below. The script will wget a new config file, but then I am stuck trying to replace a variable in the config file with the server hostname. I've had no luck getting the remote server hostname, only the local hostname (in this case MacBookPro!) will output. #!/bin/bash while read PASSWORD SERVER do sshpass -p "$PASSWORD" ssh -t -p 1234 $SERVER << ! echo "Server: $SERVER" wget -N https://example.com/file.conf 2>&1 | grep -i "failed\|error\|saved" attempt 1: replace "variabletoreplace" "$HOSTNAME" -- file.conf attempt 2: sed -i "s/variabletoreplace/$(<file.conf)/" /proc/sys/kernel/hostname end of the script: ! done <./server_list.txt I've also attempted assigning variables like host=$(hostname -f) or $HOST, but nothing will display the remote host. I understand in normal ssh commands this type of issue can be down to use of double-quotes instead of single-quotes, but I'm not sure how to amend the script I have whilst keeping it as a list of commands. Any help appreciated.
You need to escape the $ before the $HOSTNAME variable (or $(hostname) command), so that it is expanded/run on the remote machine rather than the local machine: #!/bin/bash while read PASSWORD SERVER;do sshpass -p "$PASSWORD" ssh -t -p 1234 $SERVER << EOF wget -N https://example.com/file.conf 2>&1 | grep -i "failed\|error\|saved" sed -i "s/variabletoreplace/\$HOSTNAME/" file.conf EOF done As mentioned in comments it would be much better to use ssh keys rather than sshpass and if all these commands you want to run were in a script on the remote host it would be a lot simpler. Alternatively using a tool like ansible or puppet may be more appropriate.
Output remote hostname in sshpass session
1,573,097,728,000
I set up a basic Wordpress installation (on a Raspberry Pi running Raspbian Stretch - Debian 9) using NGINX. Recently I changed the hostname of my system (as part of a plan to ensure consistent naming across my systems) and everything seemed to be working successfully. I wanted to move my Wordpress installation to a new system but found it was no longer working. The basic home page came up, but the links to logos etc did not work. It soon became obvious, as the links were attempting to access oldhostname.local and this is somewhere encoded in the Wordpress database. I restored the oldhostname and Wordpress is now working again. Looking in Settings/General Settings the oldhostname is in Wordpress Address (URL) and Site Address (URL) I could change this to my new hostname, but ideally would like to make this independent of hostname. (One aspect of the Raspberry Pi is that it is simple to clone SD Cards and I copy my installation to others with just a hostname change). My question is can I make the Wordpress installation independent of hostname, and if so how?
As far as I remember it is not possible to decouple the domain name from the WP instance, but you can change it. In the database you can find where the domain is stored by exporting the database with a mysql_dump and then search within the text file. Another method which entails running MySQL commands is explained on this blog post.. Modifying the SQL database would be the preferred method. As editing the text you might be editing the wrong fields. The commands from the blog: UPDATE wp_options SET option_value = replace(option_value, 'http://www.oldurl', 'http://www.newurl') WHERE option_name = 'home' OR option_name = 'siteurl'; UPDATE wp_posts SET guid = replace(guid, 'http://www.oldurl','http://www.newurl'); UPDATE wp_posts SET post_content = replace(post_content, 'http://www.oldurl', 'http://www.newurl'); UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.oldurl','http://www.newurl');
How to make Wordpress independent of hostname
1,573,097,728,000
I host an ubuntu server at a data center and worked well for years till last night the server can not ping itself by host name. No config has been changed. Here are what it can/can not do now. From outside, I can ping the server both by its static IP, and by its hostname. From server, I can ping any website (google, yahoo, ...). From server, I can ping localhost, and can ping the IP of server itself. From server, I can not ping sever itself by its hostname. Here is /etc/network/interfaces: source /etc/network/interfaces.d/* auto lo iface lo inet loopback auto enp5s0 iface enp5s0 inet static address xxx.xxx.xxx.134 netmask 255.255.255.128 broadcast xxx.xxx.xxx.255 gateway xxx.xxx.xxx.129 dns-nameservers 192.168.1.1 8.8.8.8 8.8.4.4 and /etc/resolv.conf: nameserver 8.8.8.8 nameserver 8.8.4.4 nameserver 192.168.1.1 nameserver 8.8.8.8 nameserver 8.8.4.4 and /etc/resolvconf/resolv.conf.d/head: nameserver 8.8.8.8 nameserver 8.8.4.4 and the output of route -n is: Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 xxx.xxx.xxx.129 0.0.0.0 UG 0 0 0 enp5s0 xxx.xxx.xxx.128 0.0.0.0 255.255.255.128 U 0 0 0 enp5s0 172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0 These configs worked for years. Wondering what happened? Thanks.
Check /etc/hosts. Probably there's a line with the name of the server and an incorrect IP
From server cannot ping server itself by its hostname while can ping by its IP
1,573,097,728,000
I'm following this guide https://www.linuxtechi.com/configure-domainkeys-with-postfix-on-centos-7/ When I get to this section, it gives an error # opendkim-default-keygen Generating default DKIM keys: Cannot determine host's domain name, so skipping default key generation. I do have my hostname set # hostname domain.org # cat /etc/hostname domain.org # cat /etc/hosts # Your system has configured 'manage_etc_hosts' as True. # As a result, if you wish for changes to this file to persist # then you will need to either # a.) make changes to the master file in /etc/cloud/templates/hosts.redhat.tmpl # b.) change or remove the value of 'manage_etc_hosts' in # /etc/cloud/cloud.cfg or cloud-config from user-data # # The following lines are desirable for IPv4 capable hosts 127.0.0.1 domain domain.org 127.0.0.1 localhost.localdomain localhost 127.0.0.1 localhost4.localdomain4 localhost4 # The following lines are desirable for IPv6 capable hosts ::1 domain domain.org ::1 localhost.localdomain localhost ::1 localhost6.localdomain6 localhost6 # cat /etc/sysconfig/network NETWORKING=yes HOSTNAME=domain.org NOZEROCONF=yes (I replaced all instances of the domain name with domain.) Other pages on the web only say to set the hostname, which is set. # cat /etc/centos-release CentOS Linux release 7.5.1804 (Core)
Thanks to RubberStamp's comment, I just viewed the opendkim-default-keygen file and copied & pasted each line manually in another window. # less /usr/sbin/opendkim-default-keygen [root@domain postfix]# prog=opendkim [root@domain postfix]# KEYGEN=/usr/sbin/$prog-genkey [root@domain postfix]# DKIM_SELECTOR=default [root@domain postfix]# DKIM_KEYDIR=/etc/$prog/keys [root@domain postfix]# ls /etc/opendkim keys KeyTable SigningTable TrustedHosts [root@domain postfix]# ls /etc/opendkim/keys [root@domain postfix]# hostname --domain [root@domain postfix]# mkdir -p $DKIM_KEYDIR [root@domain postfix]# $KEYGEN -D $DKIM_KEYDIR -s $DKIM_SELECTOR -d domain.org [root@domain postfix]# chown -R root:$prog $DKIM_KEYDIR [root@domain postfix]# chmod 640 $DKIM_KEYDIR/$DKIM_SELECTOR.private [root@domain postfix]# chmod 644 $DKIM_KEYDIR/$DKIM_SELECTOR.txt
Generating default DKIM keys: Cannot determine host's domain name, so skipping default key generation
1,573,097,728,000
I'm trying to figure out what this (obretschlt2-w7) is, from my command-line prompt. I'm using a conda environment, with the name µ_env, with my Username mu. However I can't figure out where the 2nd field is coming from. I'm logged into a secure server VPN, through my work, but I don't ever recall seeing this. What is this name and where is it coming from? (µ_env) obretschlt2-w7:~ mu$ pwd /Users/mu Output from echo $PS1, as asked for (in comment). (µ_env) \h:\W \u\$
Is that not your hostname on your system? Try: cat /etc/hostname Edit: $ echo $PS1 (µ_env) \h:\W \u\$ \h means hostname Source: wiki.ubuntuusers.de/Bash/Prompt Command "hostname" may also show your hostname
What is this random name in my command-line prompt? [duplicate]
1,573,097,728,000
im using this script to change hostname via ssh but i got some errors. read -p "Insira o IP : " ip read -p "Insira o nome do utilizador : " host read -s -p "Insira a palavra passe : " oldpass sshpass -p $oldpass ssh $host@$ip "cat /etc/hostname > hostname.txt"\ run="sshpass -p $oldpass ssh $host@$ip" \ hostn=$($run "cat hostname.txt") \ echo $hostn sshpass -p $oldpass ssh $host@$ip " \ echo "Enter new hostname: " \ read newhost \ sed -i "s/$hostn/$newhost/g" /etc/hosts \ sed -i "s/$hostn/$newhost/g" /etc/hostname \ echo "Your new hostname is "$newhost"" \ read -s -n 1 -p "Press any key to reboot" \ reboot" When i write new hostname appear that: unable to resolve host"=. But the script continued work and do reboot.
Instead of replacing name in /etc/hostname file use below command to change hostname if it is a RHEL7/CentOs7 machine hostnamectl set-hostname $newhost
Set hostname via ssh error SCRIPT
1,347,271,313,000
I have 2 graphics cards on my laptop. One is IGP and another discrete. I've written a shell script to to turn off the discrete graphics card. How can I convert it to systemd script to run it at start-up?
There are mainly two approaches to do that: With script If you have to run a script, you don't convert it but rather run the script via a systemd service: Therefore you need two files: the script and the .service file (unit configuration file). Make sure your script is executable and the first line (the shebang) is #!/bin/sh. Then create the .service file in /etc/systemd/system (a plain text file, let's call it vgaoff.service). For example: the script: /usr/bin/vgaoff the unit file: /etc/systemd/system/vgaoff.service Now, edit the unit file. Its content depends on how your script works: If vgaoff just powers off the gpu, e.g.: exec blah-blah pwrOFF etc then the content of vgaoff.service should be: [Unit] Description=Power-off gpu [Service] Type=oneshot ExecStart=/usr/bin/vgaoff [Install] WantedBy=multi-user.target If vgaoff is used to power off the GPU and also to power it back on, e.g.: start() { exec blah-blah pwrOFF etc } stop() { exec blah-blah pwrON etc } case $1 in start|stop) "$1" ;; esac then the content of vgaoff.service should be: [Unit] Description=Power-off gpu [Service] Type=oneshot ExecStart=/usr/bin/vgaoff start ExecStop=/usr/bin/vgaoff stop RemainAfterExit=yes [Install] WantedBy=multi-user.target Without script For the most trivial cases, you can do without the script and execute a certain command directly: To power off: [Unit] Description=Power-off gpu [Service] Type=oneshot ExecStart=/bin/sh -c "echo OFF > /whatever/vga_pwr_gadget/switch" [Install] WantedBy=multi-user.target To power off and on: [Unit] Description=Power-off gpu [Service] Type=oneshot ExecStart=/bin/sh -c "echo OFF > /whatever/vga_pwr_gadget/switch" ExecStop=/bin/sh -c "echo ON > /whatever/vga_pwr_gadget/switch" RemainAfterExit=yes [Install] WantedBy=multi-user.target Enable the service Once you're done with the files, enable the service: systemctl enable vgaoff.service It will start automatically on next boot. You could even enable and start the service in one go with systemctl enable --now vgaoff.service as of systemd v.220 (on older setups you'll have to start it manually). For more details see systemd.service manual page. Troubleshooting How to see full log of a systemd service? systemd service exit codes and status information explanation
How to write startup script for Systemd?
1,347,271,313,000
I just switched to debian jessie, and most things run okay, including my graphical display manager wdm. The thing is, I just don't understand how this works. Obviously my /etc/init.d/wdm script is called, because when I put an early exit in there, wdm is not started. But when I alternatively rename the /etc/rc3.d directory (my default runlevel used to be 3), then wdm is still started. I could not find out how systemd finds this script and I do not understand what it does to all the other init.d scripts. When and how does systemd run init.d scrips? In the long run, should I get rid of all init.d scripts?
chaos' answer is what some documentation says. But it's not what systemd actually does. (It's not what van Smoorenburg rc did, either. The van Smoorenburg rc most definitely did not ignore LSB headers, which insserv used to calculate static orderings, for starters.) The Freedesktop documentation, such as that "Incompatibilities" page, is in fact wrong, on these and other points. (The HOME environment variable in fact is often set, for example. This went wholly undocumented anywhere for a long time. It's now documented in the manual, at least, but that Freedesktop WWW page still hasn't been corrected.) The native service format for systemd is the service unit. systemd's service management proper operates solely in terms of those, which it reads from one of nine directories where (system-wide) .service files can live. /etc/systemd/system, /run/systemd/system, /usr/local/lib/systemd/system, and /usr/lib/systemd/system are four of those directories. The compatibility with van Smoorenburg rc scripts is achieved with a conversion program, named systemd-sysv-generator. This program is listed in the /usr/lib/systemd/system-generators/ directory and is thus run automatically by systemd early in the bootstrap process at every boot, and again every time that systemd is instructed to re-load its configuration later on. This program is a generator, a type of ancillary utility whose job is to create service unit files on the fly, in a tmpfs where three more of those nine directories (which are intended to be used only by generators) are located. systemd-sysv-generator generates the service units that run the van Smoorenburg rc scripts from /etc/init.d, if it doesn't find a native systemd service unit by that name already existing in the other six locations. systemd service management only knows about service units. These automatically (re-)generated service units are written to invoke the van Smoorenburg rc scripts. They have, amongst other things: [Unit] SourcePath=/etc/init.d/wibble [Service] ExecStart=/etc/init.d/wibble start ExecStop=/etc/init.d/wibble stop Received wisdom is that the van Smoorenburg rc scripts must have an LSB header, and are run in parallel without honouring the priorities imposed by the /etc/rc?.d/ system. This is incorrect on all points. In fact, they don't need to have an LSB header, and if they do not systemd-sysv-generator can recognize the more limited old RedHat comment headers (description:, pidfile:, and so forth). Moreover, in the absence of an LSB header it will fall back to the contents of the /etc/rc?.d symbolic link farms, reading the priorities encoded into the link names and constructing a before/after ordering from them, serializing the services. Not only are LSB headers not a requirement, and not only do they themselves encode before/after orderings that serialize things to an extent, the fallback behaviour in their complete absence is actually significantly non-parallelized operation. The reason that /etc/rc3.d didn't appear to matter is that you probably had that script enabled via another /etc/rc?.d/ directory. systemd-sysv-generator translates being listed in any of /etc/rc2.d/, /etc/rc3.d/, and /etc/rc4.d/ into a native Wanted-By relationship to systemd's multi-user.target. Run levels are "obsolete" in the systemd world, and you can forget about them. Further reading systemd-sysv-generator. systemd manual pages. Freedesktop.org. "Environment variables in spawned processes". systemd.exec. systemd manual pages. Freedesktop.org. https://unix.stackexchange.com/a/394191/5132 https://unix.stackexchange.com/a/204075/5132 https://unix.stackexchange.com/a/196014/5132 https://unix.stackexchange.com/a/332797/5132
How does systemd use /etc/init.d scripts?
1,347,271,313,000
I think I read something a while back about this, but I can't remember how it's done. Essentially, I have a service in /etc/init.d which I'd like to start automatically at boot time. I remember it has something to do with symlinking the script into the /etc/rc.d directory, but I can't remember at the present. What is the command for this? I believe I'm on a Fedora/CentOS derivative.
If you are on a Red Hat based system, as you mentioned, you can do the following: Create a script and place it in /etc/init.d (e.g., /etc/init.d/myscript).  The script should have the following format: #!/bin/bash # chkconfig: 2345 20 80 # description: Description comes here.... # Source function library. . /etc/init.d/functions start() { # code to start app comes here # example: daemon program_name & } stop() { # code to stop app comes here # example: killproc program_name } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; status) # code to check status of app comes here # example: status program_name ;; *) echo "Usage: $0 {start|stop|status|restart}" esac exit 0 The format is pretty standard, and you can view existing scripts in /etc/init.d. You can then use the script like so /etc/init.d/myscript start or chkconfig myscript start. The chkconfig man page explains the header of the script (chkconfig: 2345 20 80): This says that the script should be started in levels 2, 3, 4, and 5, that its start priority should be 20, and that its stop priority should be 80. The example start, stop and status code uses helper functions defined in /etc/init.d/functions. Enable the script: $ chkconfig --add myscript $ chkconfig --level 2345 myscript on Check that the script is indeed enabled – you should see "on" for the levels you selected. $ chkconfig --list | grep myscript
How can I make a script in /etc/init.d start at boot?
1,347,271,313,000
I have set my environment variable using /etc/profile: export VAR=/home/userhome Then if I do echo $VAR it shows /home/userhome But when I put reference to this variable into the /etc/init.d/servicename file, it cannot find this variable. When I run service servicename status using /etc/init.d/servicename file with following content: case "$1" in status) cd $VAR/dir ;; esac it says /dir: No such file or directory But it works if I run /etc/init.d/servicename status instead of service servicename status How can I make unix service see environment variables?
The problem is service strips all environment variables but TERM, PATH and LANG which is a good thing. If you are executing the script directly nothing removes the environment variables so everything works. You don't want to rely on external environment variables because at startup the environment variable probably isn't present and your init system probably won't set it anyway. If you still want to rely on such variables, source a file and read the variables from it, e.g. create /etc/default/servicename with the content: VAR=value and source it from your init script, e.g: [ -f /etc/default/service-name ] && . /etc/default/service-name if [ -z "$VAR" ] ; then echo "VAR is not set, please set it in /etc/default/service-name" >&2 exit 1 fi case "$1" in status) cd "$VAR"/dir ;; esac
How to make unix service see environment variables?
1,347,271,313,000
I am currently trying to understand the difference between init.d and cron @reboot for running a script at startup/booting of the system. The use of @reboot (this method was mentioned in this forum by hs.chandra) is some what simpler, by simply going into crontab -e and creating a @reboot /some_directory/to_your/script/your_script.txt and then your_script.txt shall be executed every time the system is rebooted. An in depth explanation of @reboot is here Alternatively by embedding /etc/init.d/your_script.txt into the second line of your script ie: #!/bin/bash # /etc/init.d/your_script.txt You can run chmod +x /etc/init.d/your_script.txt and that should also result for your_script.txt to run every time the system is booted. What are the key differences between the two? Which is more robust? Is there a better one out of the two? Is this the correct way of embedding a script to run during booting? I will be incorporating a bash .sh file to run during startup.
init.d, also known as SysV script, is meant to start and stop services during system initialization and shutdown. (/etc/init.d/ scripts are also run on systemd enabled systems for compatibility). The script is executed during the boot and shutdown (by default). The script should be an init.d script, not just a script . It should support start and stop and more (see Debian policy) The script can be executed during the system boot (you can define when). crontab (and therefore @reboot). cron will execute any regular command or script, nothing special here. any user can add a @reboot script (not just root) on a Debian system with systemd: cron's @reboot is executed during multi-user.target. on a Debian system with SysV (not systemd), crontab(5) mention: Please note that startup, as far as @reboot is concerned, is the time when the cron(8) daemon startup. In particular, it may be before some system daemons, or other facilities, were startup. This is due to the boot order sequence of the machine. it's easy to schedule the same script at boot and periodically. /etc/rc.local is often considered to be ugly or deprecated (at least by redhat), still it had some nice features: rc.local will execute any regular command or script, nothing special here. on a Debian system with SysV (not systemd): rc.local was (almost) the last service to start. but on a Debian system with systemd: rc.local is executed after network.target by default (not network-online.target !) Regarding systemd's network.target and network-online.target, read Running Services After the Network is up.
Running a script during booting/startup; init.d vs cron @reboot
1,347,271,313,000
I'm running Ubuntu where I have the directories /etc/rc0.d, /etc/rc1.d, /etc/rc2.d, ..., /etc/rc6.d. Example files from my machine: directory example symlinks in the dir ------------------------------------------ /etc/rc1.d: K76dovecot, K77ntp /etc/rc2.d: S23ntp, S24dovecot /etc/rc3.d: S23ntp, S24dovecot /etc/rc4.d: S23ntp, S24dovecot /etc/rc5.d: S23ntp, S24dovecot Questions: What's the purpose of the multiple "rc" directories? Why did Ubuntu install duplicates of dovecot and ntp into all the directories except rc0.d and rc6.d? If they are specified multiple times like above, are they actually executed multiple times? Can you tell from the above in what order dovecot and ntp will execute at startup? What is the proper way to tell Ubuntu to always execute ntp before dovecot at startup?
These are runlevels and are a System V-style initiation used by most *NIX systems (with the notable exception of systemd-based systems). When booting the kernel/user decides what runlevel should it run and execute only that runlevel. Meaning that depending the runlevel you can boot up with a different set of programs. There are runlevels for halt and reboot too, but since you are focusing on the startup part, let's ignore them for now. Since only one runlevel is executed at boot, some programs should/want to start/stop at different runlevels with different or same parameters in the same or different order (not all runlevels are the same in all OS's). But Ubuntu copy runlevels 3-5 from 2, that's why they are the same. No. runlevels are executed just once in startup or when you change runlevel. ntp scripts should execute first then dovecot in runlevel 2-5, not the case for runlevel 1. The ordinal number in the script names (S23ntp) states the order of execution. So, it all depends of the runlevel you are using. It depends of the Distro but in the particular case of Ubuntu you can add your script to runlevel 1 and 2. More info in the Wikipedia article about Ubuntu runlevels
The rc0.d,rc1.d,... directories in /etc
1,347,271,313,000
I created a startup script to start/restart/stop a group of applications. I used the lib /etc/init.d/functions in my script. It is working well on my system, but it not working for my client; he is getting the error: No such file or directory /etc/init.d/functions Right now I don't know which linux distro my client uses. Is the init.d/functions file different for different Linux distros? If so, how can I find it?
It's specific to whatever distribution you're running. Debian and Ubuntu have /lib/lsb/init-functions; SuSE has /etc/rc.status; none of them are compatible with the others. In fact, some distributions don't use /etc/init.d at all, or use it in an incompatible way (Slackware and Arch occur to me off the top of my head; there are others).
No such file or directory /etc/init.d/functions
1,347,271,313,000
I am learning command line from a book called "Linux Command Line and Shell Scripting Bible, Second Edition." The book states this: Some Linux implementations contain a table of processes to start automatically on bootup. On Linux systems, this table is usually located in the special file /etc/inittabs. Other systems (such as the popular Ubuntu Linux distribution) utilize the /etc/init.d folder, which contains scripts for starting and stopping individual applications at boot time. The scripts are started via entries under the /etc/rcX.d folders, where X is a run level. Probably because I am new to linux, I did not understand what the second paragraph quoted meant. Can someone explain the same in a much plainer language?
Let's forget init.d or rcx.d and keep things very simple. Imagine you were programming a program whose sole responsibility is to run or kill other scripts one by one. However your next problem is to make sure they run in order. How would you perform that? And lets imagine this program looked inside a scripts folder for running the scripts. To order the priority of scripts you would name them in lets say numerical order. This order is what dictates the relation between init.d and rc In other words init.d contains the scripts to run and the rcX.d contains their order to run. The X value in rcX.d is the run level. This could be loosely translated to the OS current state. If you dig inside the rcX.d scripts you will find this formatting: Xxxabcd X is replaced with K or S, which stands for whether the script should be killed or started in the current run level xx is the order number abcd is the script name (the name is irrelevant however where it points is the script this will run)
What's the connection between "/etc/init.d" and "/etc/rcX.d" directories in Linux?
1,347,271,313,000
It is not quite official but it looks like systemd is coming to Debian and after reading some of the heated mailing list discussion on that decision, I am curious about the polarizing nature of systemd among linux users. I run Debian (sysvinit) and Gentoo (OpenRC) systems and know nothing concrete about systemd, though it looks like it is coming my way. I have seen this related question asking the pros and cons of systemd vs upstart, but it has been 3 years since that question was posted and I'm sure things have changed in that time. My question is: How does systemd compare to other init systems? What sets it apart -- what can it do that the other init systems cannot? Is there anything to lose in switching to it from another init system? How does administering systemd compare to the others?
Probably everything you want to know is here on the "Debate Init System To Use" pages that the Debian project put together around making the decision of which initsystem to go with. Within that page is a separate link to each of the choices of initsystems. Debate initsystem upstart Debate initsystem systemd For a primer on Systemd this page has pretty much everything one would need to know to get started with it, RHEL7: How to get started with Systemd. Additional resources that I found helpful in getting a better understanding of the 2 primary choices I'd also read the Wikipedia pages on the respective technologies: https://en.wikipedia.org/wiki/Upstart https://en.wikipedia.org/wiki/Systemd The Gentoo project also maintains a nice comparison of some of the key features across the various initsytems: Talk:Comparison of init systems My take on your questions Q#1: How does systemd compare to other init systems? This is a very tough question to address in the space of an SE answer so I'd rather defer to the various sources that I've referenced above. I'll say this though. In reading through much of the articles about systemd of the alternatives it's trying to address many aspects of what were deficient in previous tools used for starting up services on Linux systems. It has a very well thought out design and is attempting to provide it in a very modular way. systemd components     So IMO, I would say that it compares very favorably both in terms of the effort in its design, execution of that design, and the adoption of it by several larger Linux distros. Q#2: What sets it apart -- what can it do that the other init systems cannot? The are many things that sytemd can do that other systems cannot. Probably 3 of its strongest features are: Logging Resource Limiting Dealing with daemons that fork 1. logging On the logging front, systemd has instituted a new logging system called the "Journal", the service is called systemd-journald.service. This is its own topic, you can read more about it here in this article titled: Introducing the Journal. Here's an example of a user, "harald", logging in. _SERVICE=systemd-logind.service MESSAGE=User harald logged in MESSAGE_ID=422bc3d271414bc8bc9570f222f24a9 _EXE=/lib/systemd/systemd-logind _COMM=systemd-logind _CMDLINE=/lib/systemd/systemd-logind _PID=4711 _UID=0 _GID=0 _SYSTEMD_CGROUP=/system/systemd-logind.service _CGROUPS=cpu:/system/systemd-logind.service PRIORITY=6 _BOOT_ID=422bc3d271414bc8bc95870f222f24a9 _MACHINE_ID=c686f3b205dd48e0b43ceb6eda479721 _HOSTNAME=waldi LOGIN_USER=500 2 & 3. Resource limiting & daemons that fork systemd uses a novel approach here of using cgroups to both contain and resource limit any services that require forking or limiting of access to resources. excerpt Systemd has a very clever solution to the problem of tracking daemons that fork, which coincidentally happens to handle resource limiting at the same time. Where Upstart uses ptrace to watch the forking, systemd runs each daemon in a control group (requires Linux 2.6.24 or newer) from which it can not escape with any amount of forking. This allows easy resource limiting , both for forking and non-forking daemons, since control groups were made for this sort of thing. Source:Daemon Showdown: Upstart vs. Runit vs. Systemd vs. Circus vs. God Q#3: Is there anything to lose in switching to it from another init system? Probably the biggest caveat to switching to systemd over Upstart or sysV init is having to embrace a lot of new complexities. Systemd has a lot of moving parts and is extremely feature rich and with that added capabilities you'll likely be spending a fair amount of time gaining understandings around how it all works. Q#4: How does administering systemd compare to the others? As stated in my above answer to Q#3. I'l reiterate here again. Where sysV init was fairly trivial to learn how to manage and navigate in a few hours to days, Upstart will likely take you a week or more to get up to speed, while systemd will likely take you much longer, I'm anticipating taking several weeks to gain enough cursory knowledge about it, where I'll be able to both produce my own .service files, to stopping/starting services with the same ease that I now enjoy with sysV init. References Linux startup process Serious syslog problems? systemd-journald.service man page
What sets systemd apart from other init systems?
1,347,271,313,000
Whenever I try to install something using apt-get I get the error messages involving insserv. I have tried install many different packages but everything give same error. And apparently, CUPS package is doing/has done something because every error message involves it. The following are the errors displayed when I ran sudo apt-get install wine1.8 winetricks: After this operation, 716 MB of additional disk space will be used. Do you want to continue? [Y/n] y Extracting templates from packages: 100% Preconfiguring packages ... Setting up util-linux (2.27.1-6ubuntu3.1) ... insserv: warning: script 'K01cups-browsed' missing LSB tags and overrides insserv: warning: script 'cups-browsed' missing LSB tags and overrides insserv: There is a loop at service plymouth if started insserv: There is a loop between service plymouth and procps if started insserv: loop involving service procps at depth 2 insserv: loop involving service udev at depth 1 insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Max recursions depth 99 reached insserv: loop involving service speech-dispatcher at depth 1 insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: There is a loop between service cups-browsed and hwclock if started insserv: loop involving service hwclock at depth 1 insserv: There is a loop at service cups-browsed if started insserv: loop involving service networking at depth 4 insserv: There is a loop between service plymouth and urandom if started insserv: loop involving service urandom at depth 4 insserv: loop involving service mountdevsubfs at depth 2 insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: There is a loop between service cups-browsed and dns-clean if started insserv: loop involving service dns-clean at depth 1 insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: Starting cups-browsed depends on plymouth and therefore on system facility `$all' which can not be true! insserv: exiting now without changing boot order! update-rc.d: error: insserv rejected the script header dpkg: error processing package util-linux (--configure): subprocess installed post-installation script returned error exit status 1 Errors were encountered while processing: util-linux E: Sub-process /usr/bin/dpkg returned an error code (1) The contents of /etc/insserv.conf are as follows: # # All local filesystems are mounted (done during boot phase) # $local_fs +umountfs # # Low level networking (ethernet card) # $network +networking # # Named is operational # $named +named +dnsmasq +lwresd +bind9 +unbound $network # # All remote filesystems are mounted (note in some cases /usr may # be remote. Most applications that care will probably require # both $local_fs and $remote_fs) # $remote_fs $local_fs +umountnfs +sendsigs # # System logger is operational # $syslog +rsyslog +sysklogd +syslog-ng +dsyslog +inetutils-syslogd # # The system time has been set correctly # $time +hwclock # # Services which need to be interactive # <interactive> glibc udev console-screen keymap keyboard-setup console-setup cryptdisks cryptdisks-early checkfs-loop output for $ apt-cache policy cups-browsed plymouth dns-clean cups-browsed: Installed: 1.8.3-2ubuntu3 Candidate: 1.8.3-2ubuntu3 Version table: *** 1.8.3-2ubuntu3 500 500 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 Packages 100 /var/lib/dpkg/status plymouth: Installed: 0.9.2-3ubuntu13 Candidate: 0.9.2-3ubuntu13.1 Version table: 0.9.2-3ubuntu13.1 500 500 http://in.archive.ubuntu.com/ubuntu xenial-updates/main amd64 Packages *** 0.9.2-3ubuntu13 500 500 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 Packages 100 /var/lib/dpkg/status N: Unable to locate package dns-clean I don't know any other relevant information that might be important for solving this, that's why I haven't posted it. If you want more info, please feel free to ask.
First of all, the problem is that you are stuck at the boot sequencing. The boot sequencing method is decided during installation or upgrades. If there are no loops in the dependencies declared by the LSB headers of all installed init.d scripts and no obsolete scripts, the system is converted to dependency based boot sequence. We have to check for Loop in dependencies: Occurs when > There are missing LSB tags in some scripts or error in LSB tags like missing Required-Start: or Required-Stop: tags Some scripts depend on other scripts which depend on the system facility $all which cannot be true. Because the scripts depending on $all is loaded last at starting. Since it loads last, nothing can depend on it. Hence, messes up the dependency based boot sequence. Obsolete scripts: Occur when Some packages being upgraded to newer versions which may not use a script in /etc/init.d/ and the maintainer may have missed the code to remove the old script. Not our mistake. The cause is surely foreign. Goto /etc/init.d and view the file corresponding to cups-browsed and confirm that it have an LSB comment with Provides,Required-Start/Required-Stop (at least empty),Default-Start/Default-Stop in it like below. ### BEGIN INIT INFO # Provides : cups-browsed # Required-Start : # Required-Stop : # Default-Start : 2 3 4 5 # Default-Stop : 0 1 6 # Short-Description : Some info # Description : Some more info ### END INIT INFO If it's not there you have choice to add the LSB comment or completely purge the program and scripts from /etc/init.d/ and /etc/rc? files. Hope this would work. Feel free to ask if you have any doubts.
unable to install anything using apt-get because of insserv
1,347,271,313,000
I am trying to run MongoDB on a Debian 8.5 machine. When I installed the package (pre-built from percona.com), I noticed the following files: /etc/init.d/mongod (1) /lib/systemd/system/mongod.service (2) I understand that /etc/init.d/mongod is called at boot, or in other particular system states, as long as it is registered via update-rc.d. This is perfectly fine for me. The script initializes and launches the mongo daemon. It seems to have “triggers” for start, stop, restart, etc., and as far as I understand I can trigger those with sudo service mongod <action>. /lib/systemd/system/mongod.service seems to do the same thing (i.e. run mongo), but with less configuration - just one line in the ExecStart parameter: [Unit] Description=MongoDB (High-performance, schema-free document-oriented database) After=time-sync.target network.target [Service] Type=forking User=mongod Group=mongod PermissionsStartOnly=true EnvironmentFile=/etc/default/mongod ExecStart=/usr/bin/env bash -c "/usr/bin/mongod $OPTIONS > ${STDOUT} 2> ${STDERR}" PIDFile=/var/run/mongod.pid [Install] WantedBy=multi-user.target As far as I understand this can be triggered with sudo systemctl start mongod. I don’t understand if is called at boot or not. I don’t understand why the need for two of these ‘service’ files, and how can I get rid of one (possibly the one in /lib/systemd, since it is much simpler). I don’t understand if there’s any relation between the two. I have read that systemctl works on init.d scripts too, and in this case I don’t understand which of the two files will be triggered by systemctl mongod start. I think there’s some redundancy and I should choose just one of the two ways. And I want to be sure that it is called at boot callable by command (like service or systemctl). Could you help me clear my mind?
When you have both an init.d script, and a systemd .service file with the same name, systemd will use the service file for all operations. I believe the service command will just redirect to systemd. The init.d script will be ignored. Use systemd. It's new in Debian 8, but it's the default. Systemd service files are supposed to look simpler than init.d scripts. You didn't mention any specific feature you need that's not supported by the systemd service. If the service file was not included, systemd would happily use the init.d script. So the mongod package developer is telling you they think this systemd definition is better :). Look at the output of systemctl status mongod. If the service is enabled to be started at boot time, the Loaded: line will show "enabled". Otherwise you can use systemctl enable mongod. You can also include the option --now, and it will start mongod at the same time.
Confused about /etc/init.d vs. /lib/systemd/system services
1,347,271,313,000
Is ubuntu's /etc/init.d directory exactly equivalent (functionally) to what I presume to be the more standard /etc/rc.d/ (at least on arch)? Is there any particular reason canonical used init.d instead of rc.d for startup scripts?
Ubuntu uses /etc/init.d to store SysVinit scripts because Ubuntu is based on Debian and that's what Debian uses. Red Hat uses /etc/rc.d/init.d. I forget what Slackware uses. There just isn't a standard location. Ubuntu briefly switched from SysVinit to Upstart, but has now turned to using systemd.
/etc/rc.d vs /etc/init.d
1,347,271,313,000
I was going through a tutorial on setting up a custom initramfs where it states: The only thing that is missing is /init, the executable in the root of the initramfs that is executed by the kernel once it is loaded. Because sys-apps/busybox includes a fully functional shell, this means you can write your /init binary as a simple shell script (instead of making it a complicated application written in Assembler or C that you have to compile). and gives an example of init as a shell script that starts with #!/bin/busybox sh So far, I was under the impression that init is the main process that is launched and that all the other user space process are eventually children of init. However, in the given example, the first process is actually bin/busybox/ sh from which later init is spawned. Is this a correct interpertation? If I were, for example, have a available interpreter available at that point, I could write init as a Python script etc.?
init is not "spawned" (as a child process), but rather exec'd like this: # Boot the real thing. exec switch_root /mnt/root /sbin/init exec replaces the entire process in place. The final init is still the first process (pid 1), even though it was preceded with those in the Initramfs. The Initramfs /init, which is a Busybox shell script with pid 1, execs to Busybox switch_root (so now switch_root is pid 1); this program changes your mount points so /mnt/root will be the new /. switch_root then again execs to /sbin/init of your real root filesystem; thereby it makes your real init system the first process with pid 1, which in turn may spawn any number of child processes. Certainly it could just as well be done with a Python script, if you somehow managed to bake Python into your Initramfs. Although if you don't plan to include busybox anyway, you would have to painstakingly reimplement some of its functionality (like switch_root, and everything else you would usually do with a simple command). However, it does not work on kernels that do not allow script binaries (CONFIG_BINFMT_SCRIPT=y), or rather in such a case you'd have to start the interpreter directly and make it load your script somehow.
Can the init process be a shell script in Linux?
1,347,271,313,000
What is the reason for the root filesystem being mounted ro in the initramfs (and in initrd). For example the Gentoo initramfs guide mounts the root filesystem with: mount -o ro /dev/sda1 /mnt/root Why not the following? mount -o rw /dev/sda1 /mnt/root I can see that there is a probably a good reason (and it probably involves switchroot), however it does not seem to be documented anywhere.
The initial ramdisk (initrd) is typically a stripped-down version of the root filesystem containing only that which is needed to mount the actual root filesystem and hand off booting to it. The initrd exists because in modern systems, the boot loader can't be made smart enough to find the root filesystem reliably. There are just too many possibilities for such a small program as the boot loader to cover. Consider NFS root, nonstandard RAID cards, etc. The boot loader has to do its work using only the BIOS plus whatever code can be crammed into the boot sector. The initrd gets stored somewhere the boot loader can find, and it's small enough that the extra bit of space it takes doesn't usually bother anyone. (In small embedded systems, there usually is no "real" root, just the initrd.) The initrd is precious: its contents have to be preserved under all conditions, because if the initrd breaks, the system cannot boot. One design choice its designers made to ensure this is to make the boot loader load the initrd read-only. There are other principles that work toward this, too, such as that in the case of small systems where there is no "real" root, you still mount separate /tmp, /var/cache and such for storing things. Changing the initrd is done only rarely, and then should be done very carefully. Getting back to the normal case where there is a real root filesystem, it is initially mounted read-only because initrd was. It is then kept read-only as long as possible for much the same reasons. Any writing to the real root that does need to be done is put off until the system is booted up, by preference, or at least until late in the boot process when that preference cannot be satisfied. The most important thing that happens during this read-only phase is that the root filesystem is checked to see if it was unmounted cleanly. That is something the boot loader could certainly do instead of leaving it to the initrd, but what then happens if the root filesystem wasn't unmounted cleanly? Then it has to call fsck to check and possibly fix it. So, where would initrd get fsck, if it was responsible for this step instead of waiting until the handoff to the "real" root? You could say that you need to copy fsck into the initrd when building it, but now it's bigger. And on top of that, which fsck will you copy? Linux systems regularly use a dozen or so different filesystems. Do you copy only the one needed for the real root at the time the initrd is created? Do you balloon the size of initrd by copying all available fsck.foo programs into it, in case the root filesystem later gets migrated to some other filesystem type, and someone forgets to rebuild the initrd? The Linux boot system architects wisely chose not to burden the initrd with these problems. They delegated checking of the real root filesystem to the real root filesystem, since it is in a better position to do that than the initrd. Once the boot process has proceeded far enough that it is safe to do so, the initrd gets swapped out from under the real root with pivot_root(8), and the filesystem is remounted in read-write mode.
Why does initramfs mount the root filesystem read-only
1,347,271,313,000
I'm confused as to which is best and in which circumstances: invoke-rc.d apache2 restart or service apache2 restart Is there a real difference? man service has the following interesting bit: service runs a System V init script in as predictable environment as possible, removing most environment variables and with current working directory set to /. I'm interested mainly in Debian, but also Mint (also based on Debian).
The official Debian wiki page on daemons says to use service: # service ssh restart Restarting OpenBSD Secure Shell server: sshd. Functionally service and invoke-rc.d are mostly equivalent, however: invoke-rc.d is the preferred command for packages' maintainer scripts, according to the command's man page service has a unique --status-all option, that queries status of all available daemons It seems like service is the user-oriented command, while invoke-rc.d is there for other uses.
Should "invoke-rc.d" or "service" be used to restart services?
1,347,271,313,000
I managed to create a small and fully functional live Linux CD which contains only kernel (compiled with default options) and BusyBox (compiled with default options + static, all applets present, including /sbin/init). I had no issues to create initrd and populate /dev, /proc and /sys and also I had no issues at all with my /init shell script. Recently I read that BusyBox supports /etc/inittab configurations (at least to some level) and I very much would like to do either of the following: Forget about my /init shell script and rely entirely on /etc/inittab configuration. Use both /init shell script and /etc/inittab configuration. Now the actual problem - it seems that /etc/inittab is completely ignored when my distro boots up. The symptoms are: When I remove /init and leave only /etc/inittab I end up with kernel panic. My assumption is that kernel doesn't execute /sbin/init at all, or that /sbin/init doesn't find (or read) /etc/inittab. I read that BusyBox should work fine even without /etc/inittab. So, I removed both /init and /etc/inittab and guess what - kernel panic again. I tried to execute /sbin/init from my shell and after several guesses which included exec /sbin/init, setsid /sbin/init and exec setsid /sbin/init I ended up with kernel panic. Both with and without /etc/inittab being present on the file system. Here is the content of my /init shell script: #!/bin/sh dmesg -n 1 mount -t devtmpfs none /dev mount -t proc none /proc mount -t sysfs none /sys setsid cttyhack /bin/sh At this point I don't care what the content of the /etc/inittab would be, as long as I have a way to know that the configuration there actually works. I tried several /etc/inittab configurations, all based on the information which I found here. As a bare minimum my /etc/inittab contained just this one line: ::sysinit:/bin/sh Again - I ended up with kernel panic and it seems that /etc/inittab was ignored. Any suggestions how to force my little live distro to work fine with BusyBox's /etc/inittab are highly appreciated! Update: Just to make it clear - I do not have kernel panic troubles with my current /init shell script both with and without /etc/inittab. It all works fine, my /bin/ash console works great and I don't experience any unexpected troubles. The only issue is that /etc/inittab is completely ignored, as I described above. I examined 3 different live Linux distributions: Slax, Finnix and SysResCD. All of them have /init and none of them have /etc/inittab. In addition this Wiki article concludes my suspicion that /sbin/init is not invoked at all.
OK, I did a lot of extensive research and I found out what was wrong. Let's start one by one: When we use initramfs boot scheme the first process which the kernel invokes is the /init script. The kernel will never try to execute /sbin/init directly. /init is assigned process identifier 1. This is very important! The problem now is that /sbin/init can only be started as PID 1 but we are already running /init as PID 1. The solution is to execute the command line exec /sbin/init while we are still inside /init. In this way the new process (which is /sbin/init) will inherit the PID from its parent (/init with PID 1) and that's all we have to do. The problem I experienced with my initial configuration (see the question) was due to the fact that the last thing my /init script does is to spawn new /bin/sh process which is assigned brand new PID. From this point it's impossible to run /sbin/init directly from interactive console because even when we execute the command line exec /sbin/init, the best we achieve is to assign the same PID which has already been assigned to the shell and this PID is definitely not PID 1. Long story short - execute the command line exec /sbin/init directly from /init and that's all.
Minimal Linux with kernel and BusyBox: /etc/inittab is ignored, only /init is executed
1,347,271,313,000
I found lots of good documentation for ubuntu's start-stop-daemon and there is a man page for a binary daemon. But from what I can tell the canonical way to start a daemon in a rhel/centos script is to source /etc/init.d/functions then use the daemon() function. But I can't find any good examples or documentation. What is the canonical way to start a daemon in rhel/centos-6 init script? my first attempt was: #!/bin/bash source /etc/init.d/functions daemon --user USER nohup /path/to/your/binary arg1 arg2 >/dev/null 2>&1 &
The documentation and example you are looking for is located at /usr/share/doc/initscripts-*/sysvinitfiles on CentOS/RHEL. Here is the documentation for the daemon function specifically: daemon [ --check ] [ --user ] [+/-nicelevel] program [arguments] [&] Starts a daemon, if it is not already running. Does other useful things like keeping the daemon from dumping core if it terminates unexpectedly. --check <name>: Check that <name> is running, as opposed to simply the first argument passed to daemon(). --user <username>: Run command as user <username> With CentOS/RHEL 6, you also have the option of using an upstart job file instead of writing a sysv init script.
what is the canonical way to start a daemon in rhel/centos-6 init script?
1,347,271,313,000
I've got a shell script, which is essentially a one liner with some logging, which I'm trying to run this from an init script. I'm using the daemon function inside of /etc/init.d/functions to run it, as Redhat does not appear to have start-stop-daemon available. When I call the init script (/etc/init.d/script start) it stays in the foreground, rather than completing and leaving the process running. What's the proper way for me to get this script daemonized? Script to be run: # conf file where variables are defined . /etc/script.conf echo "Starting..." | logger -i echo "Monitoring $LOG_LOCATION." | logger -i echo "Sending to $MONITOR_HOST:$MONITOR_PORT." | logger -i tail -n 1 -F $LOG_LOCATION | grep WARN --line-buffered | /usr/bin/nc -vv $MONITOR_HOST $MONITOR_PORT 2>&1 | logger -i init script: #!/bin/bash # Source Defaults . /etc/default/script # Source init functions . /etc/init.d/functions prog=/usr/local/bin/script.sh [ -f /etc/script.conf ] || exit 1 RETVAL=0 start() { # Quit if disabled if ! $ENABLED; then echo "Service Disabled in /etc/default/script" exit 1 fi echo "Starting $prog" daemon $prog RETVAL=$? return $RETVAL } stop () { echo -n $"Stopping $prog: " killproc $prog RETVAL=$? return $RETVAL } reload() { echo "Reload command is not implemented for this service." return $RETVAL } restart() { stop start } condrestart() { echo "Not Implemented." } # See how we were called. case "$1" in start) start ;; stop) stop ;; status) status $prog ;; restart) restart ;; reload) reload ;; condrestart) condrestart ;; *) echo $"Usage: $0 {start|stop|status|restart|condrestart|reload}" RETVAL=1 esac Last ~20 lines of execution with bash -vx: + case "$1" in + start + true + echo 'Starting /usr/local/bin/script.sh' Starting /usr/local/bin/script.sh + daemon /usr/local/bin/script.sh + local gotbase= force= + local base= user= nice= bg= pid= + nicelevel=0 + '[' /usr/local/bin/script.sh '!=' /usr/local/bin/script.sh ']' + '[' -z '' ']' + base=script.sh + '[' -f /var/run/script.sh.pid ']' + '[' -n '' -a -z '' ']' + ulimit -S -c 0 + '[' -n '' ']' + '[' color = verbose -a -z '' ']' + '[' -z '' ']' + initlog -q -c /usr/local/bin/script.sh
I found a script at http://www.linuxforums.org/forum/programming-scripting/190279-daemon-etc-init-d-functions-does-not-return-launching-process.html#post897522 which I was able to modify to suit my needs. It manually tracks the PID and creates a PID file using pidof. I ended up having to modify this to use pgrep as pidof was unable to see the PID of my script. After that modification, it worked fine. *Note, pgrep seems to only work if the full script name is under 15 characters long Here's what I ended up with: #!/bin/bash # # # # Start on runlevels 3, 4 and 5. Start late, kill early. # chkconfig: 345 95 05 # # #!/bin/bash # absolute path to executable binary progpath='/usr/local/bin/script.sh' # arguments to script opts='' # binary program name prog=$(basename $progpath) # pid file pidfile="/var/run/${prog}.pid" # make sure full path to executable binary is found ! [ -x $progpath ] && echo "$progpath: executable not found" && exit 1 eval_cmd() { local rc=$1 if [ $rc -eq 0 ]; then echo '[ OK ]' else echo '[FAILED]' fi return $rc } start() { # see if running local pids=$(pgrep $prog) if [ -n "$pids" ]; then echo "$prog (pid $pids) is already running" return 0 fi printf "%-50s%s" "Starting $prog: " '' $progpath $opts & # save pid to file if you want echo $! > $pidfile # check again if running pgrep $prog >/dev/null 2>&1 eval_cmd $? } stop() { # see if running local pids=$(pgrep $prog) if [ -z "$pids" ]; then echo "$prog not running" return 0 fi printf "%-50s%s" "Stopping $prog: " '' rm -f $pidfile kill -9 $pids eval_cmd $? } status() { # see if running local pids=$(pgrep $prog) if [ -n "$pids" ]; then echo "$prog (pid $pids) is running" else echo "$prog is stopped" fi } case $1 in start) start ;; stop) stop ;; status) status ;; restart) stop sleep 1 start ;; *) echo "Usage: $0 {start|stop|status|restart}" exit 1 esac exit $?
How can I run a shell script as a daemon under Redhat?
1,347,271,313,000
I want to create an unprivileged user to run my RhodeCode server and Celery daemon on a CentOS instance. I think the accepted definition of this is no home directory, login disabled, and no shell access? Looking over the man page for adduser I just don't see an intuitive method for doing this. Any suggestions are appreciated. Thanks.
From here (centos.org) useradd (which is the actual binary the runs when you call adduser, it just behaves differently. See here about that.) has an flag -r which is documented as follows: -r Create a system account with a UID less than 500 and without a home directory Which sounds like what you want to do.
How to create an unprivileged user in CentOS?
1,347,271,313,000
I'm quite new in Linux world, and now I'm trying to understand FHS principles. In /var/run I found about ten *.pid files like crond.pid which contain just PIDs. There are more than ten processes running in the system and just ten files. So what is their purpose and what generated them?
The purpose of these files is to provide an easy means for other processes to communicate with them (e.g. send signals). This only makes sense for long running services, that’s why you find much less such files than processes running. Usually those files are created by the service they represent, you will find a parameter like --pid-file or so in the invocation. Depending on the type of init-system you will find files for services in different places. sysv-init: /etc/init.d/ upstart: /etc/init/ systemd: /etc/systemd/
What is the meaning/purpose of *.pid files in /var/run
1,347,271,313,000
I use socat with following init script on debian 7.2 with sysVinit. It works perfectly: #!/bin/bash DESC=socat DAEMON=/usr/bin/socat LIB=/usr/lib/socat SOCAT_ARGS="-d -d -lf /var/log/socat.log" [ ! -f /etc/default/socat.conf ] || . /etc/default/socat.conf . /lib/lsb/init-functions PATH=/bin:/usr/bin:/sbin:/usr/sbin [ -x $DAEMON ] || exit 0 # # Try to increase the # of filedescriptors we can open. # maxfds () { [ -n "$SOCAT_MAXFD" ] || return [ -f /proc/sys/fs/file-max ] || return 0 [ $SOCAT_MAXFD -le 4096 ] || SQUID_MAXFD=4096 global_file_max=`cat /proc/sys/fs/file-max` minimal_file_max=$(($SOCAT_MAXFD + 4096)) if [ "$global_file_max" -lt $minimal_file_max ] then echo $minimal_file_max > /proc/sys/fs/file-max fi ulimit -n $SOCAT_MAXFD } start_socat() { start-stop-daemon --quiet --start \ --pidfile /var/run/socat.$NAME.pid \ --background --make-pidfile \ --exec $DAEMON -- $SOCAT_ARGS $ARGS < /dev/null } stop_socat() { start-stop-daemon --stop --quiet --pidfile /var/run/socat.$NAME.pid --exec $DAEMON rm -f /var/run/socat.$NAME.pid } start () { echo "Starting $DESC:" maxfds umask 027 cd /tmp if test "x$AUTOSTART" = "xnone" -o -z "x$AUTOSTART" ; then echo "Autostart disabled." exit 0 fi for NAME in $AUTOSTART ; do ARGS=`eval echo \\\$SOCAT_$NAME` echo $ARGS start_socat echo " $NAME $ARGS" done return $? } stop () { echo -n "Stopping $DESC:" for PIDFILE in `ls /var/run/socat.*.pid 2> /dev/null`; do NAME=`echo $PIDFILE | cut -c16-` NAME=${NAME%%.pid} stop_socat echo -n " $NAME" done } case "$1" in start) log_daemon_msg "Starting socat" "socat" if start ; then log_end_msg $? else log_end_msg $? fi ;; stop) log_daemon_msg "Stopping socat" "socat" if stop ; then log_end_msg $? else log_end_msg $? fi ;; reload|force-reload|restart) log_daemon_msg "Restarting socat" "socat" stop if start ; then log_end_msg $? else log_end_msg $? fi ;; *) echo "Usage: /etc/init.d/$NAME {start|stop|reload|force-reload|restart}" exit 3 ;; esac exit 0 However after an upgrade to debian 7.4 the system changed to systemd. So to run the same script on systemd I added a service that wrappes the /etc/init.d/socat script: [Unit] Description=Socat [Service] ExecStart=/etc/init.d/socat start ExecStop=/etc/init.d/socat stop [Install] WantedBy=multi-user.target When I start the service it is started but stops directly: Loaded: loaded (/usr/lib/systemd/system/socat.service; enabled) Active: inactive (dead) since Fri, 18 Apr 2014 14:09:46 +0200; 4s ago Process: 5334 ExecStart=/etc/init.d/socat start (code=exited, status=0/SUCCESS) CGroup: name=systemd:/system/socat.service Am I missing something?
Just figured out that I have to use Type=forking like described in http://www.freedesktop.org/software/systemd/man/systemd.service.html. If set to forking, it is expected that the process configured with ExecStart= will call fork() as part of its start-up. The parent process is expected to exit when start-up is complete and all communication channels are set up. The child continues to run as the main daemon process. This is the behavior of traditional UNIX daemons. If this setting is used, it is recommended to also use the PIDFile= option, so that systemd can identify the main process of the daemon. systemd will proceed with starting follow-up units as soon as the parent process exits.
Migrate socat init script to systemd
1,347,271,313,000
I have been using Linux after almost 5 years and observed that boot process has been almost abstracted. I mean, not much is visible to the user what is going on behind the scenes (Due to splash screens etc). Now, this might be good for the end users but not for the geek :) I want to bring back the verboseness of old times. Here is what I have done: I have been able to get rid of some of it by removing the "splash" and "quiet" parameters from the command line. However, I still cannot see the services being started one by one (like the ones in init.d). I assume its because of init daemon being replaced by upstart. Are there some configs file which I can tweak to bring back the verboseness of what is going on. Also, as soon as the login screen comes, it erases the boot log history. Is there a way to disable that ? Note: I know I can do that by simply switching the distro to Arch or Slackware. But I don't want to do that.
You can pass --verbose on the kernel command line (replacing quiet splash) to make upstart more verbose. See Upstart debugging. You can put console output in the global configuration file /etc/init.conf so that every job has its stdout and stderr connected to the console (by default, they're connected to /dev/null). (I'm not sure whether this in fact works; /etc/init.conf is not actually documented, I haven't tested if it's read in this way and this thread is not conclusive. Please test and report.) This directive can go into individual jobs' descriptions (/etc/init/*.conf) if you want to be selective (some already have it).
Removing abstraction from Ubuntu boot process
1,347,271,313,000
I put the following script in /etc/init.d/rc3.d on my Debian 7 but it doesn't work on my computer #! /bin/sh # . /etc/rc.d/init.d/functions # uncomment/modify for your killproc case "$1" in start) echo "Starting noip2." /usr/local/bin/noip2 ;; stop) echo -n "Shutting down noip2." killproc -TERM /usr/local/bin/noip2 ;; *) echo "Usage: $0 {start|stop}" exit 1 esac exit 0 How can I automatically run noip2 daemon when the machine is booted? Here is the full documetation from the noip2 source folder: This file describes noip2, a second-generation Linux client for the no-ip.com dynamic DNS service. NEW: This code will build and run on Solaris/Intel and BSD also. Edit the Makefile for Solaris and the various BSDs. For BSD users wanting to use a tun interface, see below. Let me know about any other changes needed for noip2 to operate correctly on your non-Linux OS. Mac OS X is a BSD variant. Please read this short file before using noip2. ########################################################################### HOW TO BUILD AN EXECUTABLE FOR YOUR SYSTEM The command make will build a binary of the noip2 client that will run on your system. If you do not have 'make' installed and you have an i686 Linux machine with libc6, a binary for i686 systems is located in the binaries directory called noip2-Linux. Copy that binary to the build directory 'cp binaries/noip2-Linux noip2' The command make install (which must be run as root) will install the various pieces to their appropriate places. This will ask questions and build a configuration data file. See below if you can't become root or can't write in /usr/local/*. ########################################################################### HOW TO USE THE CLIENT WITHOUT READING THE REST OF THIS TEXT Usual operation? /usr/local/bin/noip2 -C configure a client /usr/local/bin/noip2 run a client /usr/local/bin/noip2 -S display info about running clients /usr/local/bin/noip2 -D pid toggle the debug state for client pid /usr/local/bin/noip2 -K pid terminate client pid Have more than one internet access device? /usr/local/bin/noip2 -M -c file start additional instances ########################################################################### HOW TO START THE CLIENT The noip2 executable can be run by typing /usr/local/bin/noip2 If you want it to run automatically when the machine is booted, then place the following script in your startup directory. (/etc/init.d/rcX.d or /sbin/init.d/rcX.d or ???) ####################################################### #! /bin/sh # . /etc/rc.d/init.d/functions # uncomment/modify for your killproc case "$1" in start) echo "Starting noip2." /usr/local/bin/noip2 ;; stop) echo -n "Shutting down noip2." killproc -TERM /usr/local/bin/noip2 ;; *) echo "Usage: $0 {start|stop}" exit 1 esac exit 0 ####################################################### Where the 'X' in rcX.d is the value obtained by running the following command grep initdefault /etc/inittab | awk -F: '{print $2}' Killproc can be downloaded from ftp://ftp.suse.com/pub/projects/init Alternatively, you can uncomment the line after #! /bin/sh If you have a recent RedHat version, you may want to use the startup script supplied by another user. It's in this package called redhat.noip.sh It may need some modification for your system. There is a startup script for Debian called debian.noip2.sh. It also has been supplied by another user and is rumored to fail in some situations. Another user has supplied a proceedure to follow for MAc OS X auto startup. It's called mac.osx.startup. Mac users may wish to read that file. Here is a script which will kill all running copies of noip2. #!/bin/sh for i in `noip2 -S 2>&1 | grep Process | awk '{print $2}' | tr -d ','` do noip2 -K $i done These four lines can replace 'killproc' and 'stop_daemon' in the other scripts. If you are behind a firewall, you will need to allow port 8245 (TCP) through in both directions. ####################################################################### IMPORTANT!! Please set the permissions correctly on your executable. If you start noip2 using one of the above methods, do the following: chmod 700 /usr/local/bin/noip2 chown root:root /usr/local/bin/noip2 If you start noip2 manually from a non-root account, do the chmod 700 as above but chown the executable to the owner:group of the non-root account, and you will need to substitute your new path if the executable is not in /usr/local/bin. ########################################################################### SAVED STATE Noip2 will save the last IP address that was set at no-ip.com when it ends. This setting will be read back in the next time noip2 is started. The configuration data file must be writable for this to happen! Nothing happens if it isn't, the starting 0.0.0.0 address is left unchanged. If noip2 is started as root it will change to user 'nobody', group 'nobody'. Therefore the file must be writeable by user 'nobody' or group 'nobody' in this case! ########################################################################### BSD USING A TUN DEVICE Recent BSD systems will use getifaddrs() to list ALL interfaces. Set the 'bsd_wth_getifaddrs' define in the Makefile if using a version of BSD which supports getifaddrs() and ignore the rest of this paragraph. Mac OS X users should have a versdion of BSD which supports getifaddrs(). Otherwise set the 'bsd' define. The 'bsd' setting will not list the tun devices in BSD. Therefore a tun device cannot be selected from the menu. If you want to use a tun device you will need to edit the Makefile and change the line ${BINDIR}/${TGT} -C -Y -c /tmp/no-ip2.conf to ${BINDIR}/${TGT} -C -Y -c /tmp/no-ip2.conf -I 'your tun device' COMMAND LINE ARGUMENTS WHEN INVOKING THE CLIENT The client will put itself in the background and run as a daemon. This means if you invoke it multiple times, and supply the multiple-use flag, you will have multiple instances running. If you want the client to run once and exit, supply the '-i IPaddress' argument. The client will behave well if left active all the time even on intermittent dialup connections; it uses very few resources. The actions of the client are controlled by a configuration data file. It is usually located in /usr/local/etc/no-ip2.conf, but may be placed anywhere if the '-c new_location' parameter is passed on the startup line. The configuration data file can be generated with the '-C' parameter. There are some new command line arguments dealing with default values in the configuration data file. They are -F, -Y and -U. The interval between successive testing for a changed IP address is controlled the '-U nn' parameter. The number is minutes, a minimum of 1 is enforced by the client when running on the firewall machine, 5 when running behind a router/firewall. A usual value for clients behind a firewall is 30. One day is 1440, one week is 10080, one month is 40320, 41760, 43200 or 44640. One hour is left as an exercise for the reader :-) The configuration builder code will allow selection among the hosts/groups registered at no-ip.com for the selected user. The '-Y' parameter will cause all the hosts/groups to be selected for update. Some sites have multiple connections to the internet. These sites confuse the auto NAT detection. The '-F' parameter will force the non-NAT or "firewall" setting. The client can be invoked with the '-i IPaddress' parameter which will force the setting of that address at no-ip.com. The client will run once and exit. The -I parameter can be used to override the device name in the configuration data file or to force the supplied name into the configuration data file while it is being created. Please use this as a last resort! The '-S' parameter is used to display the data associated with any running copies of noip2. If nothing is running, it will display the contents of the configuration data file that is selected. It will then exit. The '-K process_ID' parameter is used to terminate a running copy of noip2. The process_ID value can be obtained by running noip2 -S. The '-M' parameter will permit multiple running copies of the noip2 client. Each must have it's own configuration file. Up to 4 copies may run simultaneously. All errors and informational messages are stored via the syslog facility. A line indicating a successful address change at no-ip.com is always written to the syslog. The syslog is usually /var/log/messages. If the client has been built with debugging enabled, the usual state, the '-d' parameter will activate the debug output. This will produce a trace of the running program and should help if you are having problems getting the connection to no-ip.com established. All errors, messages and I/O in both directions will be displayed on the stderr instead of syslog. The additional '-D pid' parameter will toggle the debug state of a running noip2 process. This will not change where the output of the process is appearing; if it was going to the syslog, it will still be going to the syslog. One final invocation parameter is '-h'. This displays the help screen as shown below and ends. USAGE: noip2 [ -C [ -F][ -Y][ -U #min]][ -c file] [ -d][ -D pid][ -i addr][ -S][ -M][ -h] Version Linux-2.x.x Options: -C create configuration data -F force NAT off -Y select all hosts/groups -U minutes set update interval -c config_file use alternate data path -d increase debug verbosity -D processID toggle debug flag for PID -i IPaddress use supplied address -I interface use supplied interface -S show configuration data -M permit multiple instances -K processID terminate instance PID -h help (this text) ########################################################################### HOW TO CONFIGURE THE CLIENT The command noip2 -C will create configuration data in the /usr/local/etc directory. It will be stored in a file called no-ip2.conf. If you can't write in /usr/local/*, or are unable to become root on the machine on which you wish to run noip2, you will need to include the '-c config_file_name' on every invocation of the client, including the creation of the datafile. Also, you will probably need to put the executable somewhere you can write to. Change the PREFIX= line in the Makefile to your new path and re-run make install to avoid these problems. You will need to re-create the datafile whenever your account or password changes or when you add or delete hosts and/or groups at www.no-ip.com Each invocation of noip2 with '-C' will destroy the previous datafile. Other options that can be used here include '-F' '-Y' -U' You will be asked if you want to run a program/script upon successful update at no-ip.com. If you specify a script, it should start with #!/bin/sh or your shell of choice. If it doesn't, you will get the 'Exec format error' error. The IP address that has just been set successfully will be delivered as the first argument to the script/program. The host/group name will be delivered as the second argument. Some machines have multiple network connections. In this case, you will be prompted to select the device which connects to outside world. The -I flag can be supplied to select an interface which is not shown. Typically, this would be one of the pppx interfaces which do not exist until they are active. The code will prompt for the username/email used as an account identifier at no-ip.com. It will also prompt for the password for that account. The configuration data contains no user-serviceable parts!! IMPORTANT!! Please set the permissions correctly on the configuration data. chmod 600 /usr/local/etc/no-ip2.conf. chown root:root /usr/local/etc/no-ip2.conf. If you start noip2 manually from a non-root account, do the chmod as above but chown the no-ip2.conf file to the owner:group of the non-root account. Make sure the directory is readable! The program will drop root privileges after acquiring the configuration data file. And the sample init script for debian: #! /bin/sh # /etc/init.d/noip2.sh # Supplied by no-ip.com # Modified for Debian GNU/Linux by Eivind L. Rygge <[email protected]> # corrected 1-17-2004 by Alex Docauer <[email protected]> # . /etc/rc.d/init.d/functions # uncomment/modify for your killproc DAEMON=/usr/local/bin/noip2 NAME=noip2 test -x $DAEMON || exit 0 case "$1" in start) echo -n "Starting dynamic address update: " start-stop-daemon --start --exec $DAEMON echo "noip2." ;; stop) echo -n "Shutting down dynamic address update:" start-stop-daemon --stop --oknodo --retry 30 --exec $DAEMON echo "noip2." ;; restart) echo -n "Restarting dynamic address update: " start-stop-daemon --stop --oknodo --retry 30 --exec $DAEMON start-stop-daemon --start --exec $DAEMON echo "noip2." ;; *) echo "Usage: $0 {start|stop|restart|force-reload}" exit 1 esac exit 0
Two steps for you to solve this. Your script (/etc/init.d/noip2) should look like: #! /bin/sh # /etc/init.d/noip2 # Supplied by no-ip.com # Modified for Debian GNU/Linux by Eivind L. Rygge <[email protected]> # Updated by David Courtney to not use pidfile 130130 for Debian 6. # Updated again by David Courtney to "LSBize" the script for Debian 7. ### BEGIN INIT INFO # Provides: noip2 # Required-Start: networking # Required-Stop: # Should-Start: # Should-Stop: # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start noip2 at boot time # Description: Start noip2 at boot time ### END INIT INFO # . /etc/rc.d/init.d/functions # uncomment/modify for your killproc DAEMON=/usr/local/bin/noip2 NAME=noip2 test -x $DAEMON || exit 0 case "$1" in start) echo -n "Starting dynamic address update: " start-stop-daemon --start --exec $DAEMON echo "noip2." ;; stop) echo -n "Shutting down dynamic address update:" start-stop-daemon --stop --oknodo --retry 30 --exec $DAEMON echo "noip2." ;; restart) echo -n "Restarting dynamic address update: " start-stop-daemon --stop --oknodo --retry 30 --exec $DAEMON start-stop-daemon --start --exec $DAEMON echo "noip2." ;; *) echo "Usage: $0 {start|stop|restart}" exit 1 esac exit 0 Then make it executable, i.e run # chmod a+x /etc/init.d/noip2 # update-rc.d noip2 defaults
Run automatically Noip2 when the machine is booted?
1,347,271,313,000
I'm trying to add Qemu to my continuous integration pipeline to test various initrd artifacts. I've already discovered that I can run Qemu like this: qemu-system-x86_64 \ -machine q35 \ -drive if=pflash,format=raw,file=OVMF_CODE.fd,readonly \ -drive if=pflash,format=raw,file=OVMF_VARS.fd \ -kernel vmlinuz-4.4.0-121-generic \ -initrd my-initramfs.cpio.xz \ -nographic ...and cause qemu-system-x86_64 to exit with status 0 if I do this in my init script: # poweroff -f This is works because the init script doesn't exit -- it invokes poweroff -f and sleeps "forever" or until Qemu does a "Power Down": ACPI: Preparing to enter system sleep state S5 reboot: Power down I would like to be able to detect problems in the init script by forcing an exit on error via set -eu. Exiting the init script (correctly) causes a kernel panic but the qemu-system-x86_64 process hangs forever. How can I keep it from hanging forever? How do I get the Qemu host to detect a kernel panic in the Qemu guest? Further clarification: The nature of my application is security-sensitive; i.e., configuring/compiling the linux kernel is "allowed", but passing kernel parameters is not. To put a fine point on it, CMDLINE_OVERRIDE is enabled.
I've got something that's working: Configure (and build) the kernel with CONFIG_PVPANIC=y; this produces a kernel with compiled-in support for the pvpanic device. Invoke qemu-system-x86_64 with the -device pvpanic option; this instructs Qemu to catch (and exit on) a kernel panic. A kernel panic causes qemu-system-x86_64 to exit successfully (return status 0), but at least it's not hanging anymore. Many thanks to @dsstorefile1 for pointing me in the right direction. References: https://cateee.net/lkddb/web-lkddb/PVPANIC.html https://github.com/qemu/qemu/blob/master/docs/specs/pvpanic.txt
Can I make Qemu exit with failure on kernel panic?
1,347,271,313,000
I have a init script in /etc/init.d/myservice for initialize a service like this: ... start() { ... daemon /usr/sbin/myservice ... } stop() { ... pgrep myservice pidof myservice ps -ef | grep myservice ... } And when I try to stop the service, this is the output: 10000 10001 10000 root 10000 1 0 09:52 ? 00:00:02 /usr/sbin/myservice root 9791 9788 0 10:06 pts/1 00:00:00 /bin/sh /sbin/service myservice stop root 10001 9791 1 10:06 pts/1 00:00:00 /bin/sh /etc/init.d/myservice stop root 9805 9796 0 10:06 pts/1 00:00:00 grep myservice Is this expected? Why pidof is returning only the correct PID of the service that I want to stop and pgrep is returning the service PID and the PID of the init script? Can I rely on that pidof will always ignore the PID from the init script?
pidof = find the process ID of a running program Pidof finds the process id's (pids) of the named programs. It prints those id's on the standard output. This program is on some systems used in run-level change scripts, especially when the system has a System-V like rc structure. sysadmin@codewarden:~$ pidof apache2 5098 5095 5094 5092 pgrep = look up or signal processes based on name and other attributes, pgrep looks through the currently running processes and lists the process IDs which matches the selection criteria. sysadmin@codewarden:~$ pgrep apache2 5092 5094 5095 5098 pgrep, (p) = process, grep = grep prints the matching lines Want to know more about pgrep & pidof ? Just run in terminal as # man pidof # man pgrep
Why pidof and pgrep are behaving differently?
1,347,271,313,000
Is there any real difference between /etc/init.d/networking restart and invoke-rc.d networking restart (Debian)?
What invoke-rc.d does is documented in its man page. It is a wrapper around running the init script directly, but it also applies a policy that may cause the command not to be run, based on the current runlevel and whether the daemon should be run in that runlevel. By default, Debian does not differentiate between runlevels 2-5, but as the local administrator, you can change what is run in each runlevel. invoke-rc.d will honor these local policies and not start a daemon if the runlevel is wrong.
Difference between /etc/init.d/networking restart and invoke-rc.d networking restart
1,347,271,313,000
I have several questions related to non-interactive, non-login shells and cron jobs. Q1. I have read that non-interactive, non-login shells only "load" $BASH_ENV. What does this exactly mean? Does it mean that I can point $BASH_ENV to a file, and that this file will be sourced? Q2: Assuming that I have an entry in cron pointing to a Bash script with a Bash shebang, what environment variables and definitions can I assume my Bash script is loaded with? Q3: If I add SHELL=/bin/bash to the top of my crontab, what exactly does this do? Does it mean that: cron itself runs in Bash? The commands specified in crontab are interpreted in Bash? The scripts that do not have shebangs in them, are run under $SHELL something else? Q4: How can I set BASH_ENV for cron jobs?
For Q1 & Q2, see here. Q3 is answered in the discussion of your other three questions below. WRT $BASH_ENV, from man bash: When bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. So this could be a .profile type script. As to where or who set it, this depends on context -- generally it is not set, but it could have been by any ancestor of the current process. cron does not seem to make any special use of this, and AFAIK neither does init. Does it mean that cron itself runs in Bash? If by "in" you mean, is started from a shell, then this depends on the init system -- e.g., SysV executes shell scripts for services, so those services are always started via a shell. But if by "in" you mean, "Is it thus a child of a shell process?", no. Like other daemons it runs as the leader of its own process group and its parent process is the init process (pid 1). The consequences for cron's environment are probably immaterial, however. For more about the environment of start-up services, see the answer linked above regarding Q1 & Q2. WRT to cron specifically, according to man 5 crontab it also sets some environment variables that are inherited by any process it starts ($LOGNAME, $HOME, and $SHELL). The commands specified in crontab are interpreted in Bash? They're interpreted with sh or $SHELL; again from man 5 crontab: The entire command portion of the line, up to a newline or a "%" character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the cronfile. A "%" character in the command, unless escaped with a backslash (), will be changed into newline characters, and all data after the first % will be sent to the command as standard input. The emphasized part anwsers Q3. The scripts that do not have shebangs in them, are run using $SHELL Executable scripts with or without shebangs are opened by $SHELL (or sh). The difference is, those with a shebang will then be handed to the appropriate interpreter (#!/bin/sh being another instance of the shell), whereas executable scripts (ones with the executable bit set that are reference as executables) without a shebang will simply fail, just as they would when run from the command line (unless you run them sh script.sh).
BASH_ENV and cron jobs
1,347,271,313,000
After trying to delete apache and tomcat, and now trying to reinstall apache 2, I am missing the init.d/apache2 file to start/stop my server. I am not sure if the new install actualy worked, and my apt-get purge apache2 didn't remove everything in the first place! How can I get the init.d/apache2 file to test if server starts / is installed properly (I had removed files and directories manually)?
Try using apt-get install --reinstall apache2 to force the apt-get system to install again even though the package exists and overwrite current files — even the ones it thinks are already there. By manually deleting things from the system you undoubtedly have the package manager confused about what needs doing where. You usually want to stick to using the tools provided unless you understand what you are effecting by manually fiddling. As an extra note, you don't usually need to mess with the files in /etc/init.d yourself. There is a tool that takes care of running those scripts for you. For example to restart apache you could run service apache2 restart. Edited based on information found in comments The init script is part of a sub-package. Installing a package for the first time will install it's dependencies, but uninstalling it will just uninstall the package, not it's dependencies. The init script that you manually removed belongs to the apache2.2-common package with was a dependency of the main apache2 package name. Removing apache2 even with --purge would have no effect on the init script because it's part of a different package. To get it back run apt-get install --reinstall apache2.2-common. Edit2 Apparently Debian is wacky. I replicated the problem on a test system and was unable to get the init script back with the package manager. I found several other people with the same problem out on the web, and it looks like the solution is to manually download the package, extract it, and rip the file out like this: cd /tmp aptitude download apache2.2-common dpkg --extract apache2.2-common_*.deb apache2.2-common sudo cp apache2.2-common/etc/init.d/apache2 /etc/init.d Edit3 Thanks to investigation done by Faheem Mitha and discussion on the comments below, a full answer to this question has worked out. Read Faheem's answer for full details. For humor value, here are the cliff notes: The short version is that init scripts are considered conf files, and apt-get is too polite to touch conf files that have been user-modified in any way, even to restore deleted on reinstall after a uninstall. Before you say "duh of course", check out the gymnastics you have to do. I quote: After asking the dpkg list (and being told off for it) + further fiddling, the following works. Be careful with this. It will replace all your modified config files with the version from the package. apt-get -o Dpkg::Options::="--force-confnew" -o Dpkg::Options::="--force-confask" install --reinstall apache2.2-common. I don't know why you needed me to tell you this. It's the first thing you should have thought of. :-) – Faheem Mitha
Missing init.d/apache2 file [duplicate]
1,347,271,313,000
So I have this program which I manually run as root : sudo gammu-smsd -c /etc/gammu-smsdrc -d What this does is it runs the Gammu (software to manage gsm modems) and 'daemonize' it. My problem is I want this program to automatically run on boot up . Is it ok to just edit root's crontab and stick this command there? Or there's some other way? (Im using Ubuntu 11.04.)
How about /etc/rc.local? This will be executed last in the startup sequence.
How to run a program on boot up?
1,347,271,313,000
CPU is AMD GX-412TC SOC: GX-412TC GE412TIYJ44JB 4 6W 2MB 1.0GHz/ 1.4GHz N/A N/A DDR-1333 0-90°C which does not have rdrand: grep rdrand /proc/cpuinfo # nothing I see following messages in my syslog after machine boot: kernel: random: dd: uninitialized urandom read (512 bytes read) kernel: random: cryptsetup: uninitialized urandom read (32 bytes read) what exactly do these messages mean, and what can I do about it? Does it mean dd and cryptsetup try to read from /dev/urandom, but there is not enough entropy? I am using haveged daemon, but it is started late in the boot process, after this message appears. Here is my boot script startup sequence: /etc/rcS.d/S01hostname.sh /etc/rcS.d/S01mountkernfs.sh /etc/rcS.d/S02mountdevsubfs.sh /etc/rcS.d/S03checkroot.sh /etc/rcS.d/S04checkfs.sh /etc/rcS.d/S05mountall.sh /etc/rcS.d/S06bootmisc.sh /etc/rcS.d/S06procps /etc/rcS.d/S06urandom /etc/rcS.d/S07crypto-swap /etc/rc2.d/S01haveged /etc/rc2.d/S01networking /etc/rc2.d/S04rsyslog /etc/rc2.d/S05cron /etc/rc2.d/S05ssh the messages in syslog come from these two scripts: /etc/rcS.d/S06urandom -> dd /etc/rcS.d/S07crypto-swap -> cryptsetup Should haveged be started before urandom ? I am using Debian 10. Also, I should add that this machine is a bare board, with no keyboard. The only interface is a serial console. I think this has an effect on the available entropy, and is the reason why I have installed haveged in the first place. Without haveged, the sshd daemon would not start for several minutes, because it does not have enough entropy.
For haveged to work, it has to be compatible with your kernel — there's an issue with haveged not doing anything in kernel versions >=5.x, see is haveged still useful/relevant? #57 on GitHub. The maintainer was kind enough to re-introduce functionality but those patches will have to be released and then make it into the various distros first... the old version either won't start at all or won't actually do anything even if it's running (check with strace), as the kernel's entropy pool no longer seems to be lacking — but crng init still takes time for some reason. It also has to run very early on, so if you are using initramfs, then you also have to start haveged in initramfs, some time before using the random device. In a traditional init system, haveged should run as soon as /proc /sys /dev is available. I'm not sure how long haveged takes exactly to send entropy to the kernel... it has to harvest randomness on its own first and it runs some quality tests on that too. In my last test (with patched haveged) there was like half a second delay between starting haveged and kernel reporting random: crng init done. In addition to haveged, you can also consider saving/restoring a random seed, and if you have network, a little bit of traffic might help the kernel to collect some entropy as well.
syslog message at boot: uninitialized urandom read
1,347,271,313,000
I had to write my own CentOS init.d script for celery because it only ships with one for Debian. You can see the script I wrote when I answered my own stack overflow question 3989656. But there's a problem with this script. if I invoke it: sudo service celeryd start then I need to hit enter to get a shell prompt after it completes. This is a problem because I want to invoke it via ssh from another machine by doing: ssh 192.168.2.3 sudo service celeryd start and ssh never returns. (I use fabric to start and stop remote services, and this hangs it because it invokes the ssh command above). What would cause this behavior, and how do I fix it in my script? Note that if I do "sh -x /etc/init.d/celeryd" as recommended by Thomas Themel in the comments, the output is: runuser -s /bin/bash - apache -c 'ulimit -S -c 0 >/dev/null 2>&1 ; /usr/local/django/portalapps/manage.py celeryd --pidfile /var/run/celery.pid -f /var/log/celeryd.log -l INFO' I don't understand how the daemon function in /etc/init.d/functions (which is what produces this series of bash commands) actually daemonizes the process.
Had the exact same problem - your question and investigations actually helped me find the answer. Start celery with celery_detach - and, poof! Things work! ie. manage.py celery_detach --params --settings=foo It returns immediately, with a proper line break, and the things that fabric is looking for.
Why do I need to hit enter to get my shell prompt after my init.d script completes?
1,347,271,313,000
I'm using a Raspberry Pi B, with Raspbian. After upgrading to Jessie, watchdog daemon doesn't start at boot anymore. Starting it manually using "sudo service watchdog start" does work. I tried: purging and reinstalling watchdog update-rc.d watchdog defaults && update-rc.d watchdog enable systemctl enable watchdog produces this error: The unit files have no [Install] section. They are not meant to be enabled using systemctl. I checked syslog with systemd verbosity on debug, no results. Other than the watchdog device nothing is mentioned. systemctl list-units | grep -i watchdog is emtpy (unless I started it manually) My default runlevel is 5 and the priority of watchdog in /etc/rc5.d/ is also 5. What else can I try?
Open /lib/systemd/system/watchdog.service and add [Install] WantedBy=multi-user.target Systemd needs the [Install]-Section for a Unit to know how it should enable/disable the Unit.
Watchdog daemon doesn't start at boot
1,347,271,313,000
I would like to migrate some OpenRC init script to systemd but I think that it is general problem of environment variables handling in systemd. Original OpenRC files There is a file e.g. /etc/conf.d/fooservice with contents # value of FOO variable # you can override default value by uncomenting this line # FOO=value1 # value of BAR variable BAR=value2 In original startup script /etc/init.d/fooservice, there was FOO=${FOO:-default_foo_value} BAR=${BAR:-default_bar_value} So the result was $FOO==default_foo_value and $BAR==value2 Migrated systemd files Now I have systemd service file /usr/lib/systemd/system/fooservice.service, that contains [Service] EnvironmentFile=/etc/conf.d/fooservice ExecStart=/usr/bin/fooservice $FOO $BAR But there is a problem that $FOO is not initialized to default_foo_value Is there a way to tell systemd to use default value if there is no value in environment file? Is there a way to use intermediate environment file with default values or multiple chained Environment files? SOLUTION: This is not good way. /etc/conf.d/fooservice file can be incompatible because it is "shell script" and systemd expects "environment file". In basic value assignment, it seems similar, but it is not the same thing. Prefered solution for this by Gentoo is to put everything into service file and configuration file of the service and not to use additional conf.d file. WORKING BUT NOT PREFERED SOLUTION: Use this only as fast hack to run OpenRC service as systemd one. /usr/lib/systemd/system/fooservice.service now contains [Service] Environment="FOO=default_foo_value" Environment="BAR=default_bar_value" EnvironmentFile=/etc/conf.d/fooservice ExecStart=/usr/bin/fooservice $FOO $BAR
systemd is not a shell, so it does not support shell-specific substitutions in environment files. Their format is simply KEY=VALUE, with possible empty lines and comments in between. To quote systemd.exec(5): Settings from these files override settings made with Environment=. If the same variable is set twice from these files, the files will be read in the order they are specified and the later setting will override the earlier setting. So, you can accomplish your task by either: using multiple EnvironmentFile= directives (they override each other in the order of specification) using Environment= in the service file to specify default values (any EnvironmentFile= will override it)
systemd: default value for environment variable
1,347,271,313,000
I'm running Debian wheezy. Many scripts in /etc/init.d/ use various logging functions defined in the Linux Standard Base, like log_success_msg and log_warning_msg. The LSB documentation seems a bit ambiguous as to exactly what these functions should do: The log_success_msg function shall cause the system to write a success message to an unspecified log file. The format of the message is unspecified. The log_success_msg function may also write a message to the standard output. However, I guess this is interpreted as meaning that the functions can either write to a log file or just write to standard output. It seems that on Debian at least, it just causes a message to be written to standard output. My suspicions were confirmed when I checked out the file defining these functions, /lib/lsb/init-functions - it just calls echo to display any log message. This is not helpful behaviour. Text written on boot to standard output disappears shortly after boot is complete, and may well scroll off the top of the screen in any case. Surely it would be far more helpful if these messages were actually stored in a log file; in fact I don't even see the point of logging anything via these functions if they are only going to go to standard output. Is there any way to get these logs going to a file? Can anyone enlighten me as to why you would bother "logging" anything only to standard output? What helpful function does it serve?
It looks like the solution is to install bootlogd and put BOOTLOGD_ENABLE=yes in /etc/default/bootlogd. References: bootlogd - Debian Wiki bootlogd(8) man page bug 524761 - rsyslog doesn't log boot messages (boot.log) bug 658134 - no more bootlogs
How to write init.d script log messages to disk?
1,347,271,313,000
Is there a way to run a script on shutdown, after the file system is remounted as read-only? I've a raspberry pi connected to a wireless socket, which I can control via a sender and a script. I want to power off that socket (powering off the raspberry) on shutdown, after the file system is mounted read-only. I've tried this: [Unit] Description=Test DefaultDependencies=no Requires=shutdown.target umount.target final.target After=shutdown.target umount.target final.target [Service] Type=oneshot ExecStart=/test KillMode=none [Install] WantedBy=halt.target The script /test does output the current mounts. When it's run on shutdown, it states read/write for the root file system and not read-only as expected. Edit: Content of /test: #!/bin/bash echo -n 'Debug-Mount: ' > /dev/tty1 cat /proc/mounts | grep /dev/sda > /dev/tty1 Screen output on shutdown:
I found a reliable solution: Just put the script in /usr/lib/systemd/system-shutdown/. See also: https://www.freedesktop.org/software/systemd/man/systemd-halt.service.html Immediately before executing the actual system halt/poweroff/reboot/kexec systemd-shutdown will run all executables in /usr/lib/systemd/system-shutdown/ and pass one arguments to them: either "halt", "poweroff", "reboot" or "kexec", depending on the chosen action. All executables in this directory are executed in parallel, and execution of the action is not continued before all executables finished.
systemd: running a script on shutdown after filesystems are mounted read-only
1,347,271,313,000
In order to adjust the screenpad backlight on my ASUS Zenbook, I am using a kernel module I found here. Per his instructions, to make keybind shortcuts using a simple screenpad x command to adjust the brightness, I need to add sudo chmod a+w '/sys/class/leds/asus::screenpad/brightness' to 'rc.local', as the command is required with each reboot, and needs a password every time. By running automatically I could immediately use the custom keyboard shortcuts as they'd function normally with the drivers on Windows, without needing to run the command and enter my password each boot. I'm a new Linux user, on Parrot OS. From what I've gathered, it's not recommend to use rc.local, and I should instead use either systemd, cronjob, or run it as process using the GUI startup applications menu. I'm completely lost as to go about doing this with systemd or cronjob. I tried making a file called 'screenpad-perms.sh' and put it in /usr/local/bin, with just these lines in it based on what I've read: #! /bin/bash sudo chmod a+w '/sys/class/leds/asus::screenpad/brightness' I then made it executable using chmod +x screenpad-perms.sh. Finally, I opened the GUI Autostart app and added it as a Login Script. Restarted the PC but it doesn't work, typing screenpad x gets a permissions denied error unless I manually type sudo chmod a+w '/sys/class/leds/asus::screenpad/brightness' and enter my password; so it seems to not be executing. Again apologies as I'm very new to Linux, just really hoping to get this screen working properly. What am I missing here?
If your system is using systemd, that is your best option for what you want to do. The systemd unit will already be executed as root, so sudo is not needed, and you can set it up to run during bootup without even needing anyone to be there to log in. Here's one link with information on systemd: https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files systemd unit files are more or less similar to a Microsoft *.INI file. They have [SectionHeadings] followed by Directive=Value line. Here are the steps you will need: Either load a root shell (sudo bash) or prefix most of the commands with sudo to run as root. Create a shell script for the systemd service unit to execute. Typically, you will put the file in /usr/local/sbin. Let's call it /usr/local/sbin/fix-backlight.sh (as root): editor /usr/local/sbin/fix-backlight.sh (Assuming editor launches your preferred editor and it creates the file if it does not exist.) In the file, put (the #! MUST be the first line of the file): #!/bin/bash chmod a+w '/sys/class/leds/asus::screenpad/brightness' Go ahead and save it and close your editor. Then make the file only read/write/executable by root (for security): chmod 0700 /usr/local/sbin/fix-backlight.sh Create the systemd unit file (usually in /etc/systemd/system, but there are other locations; the link above gives more detail): editor /etc/systemd/system/fix-backlight.service In the editor for that file, put: [Unit] Description=Fix perms for the 'screenpad x' backlight command [Service] ExecStart=/usr/local/sbin/fix-backlight.sh [Install] WantedBy=multi-user.target Save and exit the editor. Test the unit: systemctl start fix-backlight.service If all went well and from (a non-root) shell the 'screenpad x' cmmand is working, enable the unit to start on boot: systemctl enable fix-backlight.service Go ahead then and reboot, and make sure it's all working now. (And if it does not and blows up the neighbor's cat, blame the dog!) If needed, you can also systemctl disable fix-backlight.service to make it stop running at boot.
Running a sudo command automatically on startup
1,347,271,313,000
I have a an inittab file with the following entry: console::askfirst:-/bin/ash According to this Man page a '+' character in the process field means init will not do utmp and wtmp accounting for that process. However, it does not say anything about a '-' character. What does having the '-' character in the process field do?
The hyphen appears to be a Busybox-specific feature (as is "askfirst", which was how I found that you are using Busybox). The example inittab file says: # /bin/sh invocations on selected ttys # # Note below that we prefix the shell commands with a "-" to indicate to the # shell that it is supposed to be a login shell. Normally this is handled by # login, but since we are bypassing login in this case, BusyBox lets you do # this yourself... # # Start an "askfirst" shell on the console (whatever that may be) ::askfirst:-/bin/sh So, it starts the shell as a login shell (by beginning argv[0] with a hyphen). What a login shell means is beyond the scope of this question, but it generally at least means it will execute different startup files (i.e. ~/.profile). The convention of using a hyphen in argv[0], rather than a proper command line flag, to tell the shell it is a login shell, is an ancient convention - it dates back to at least Second Edition UNIX. (argv[0] was simply "-" for login shells until Sixth Edition, then it was changed to "-/bin/sh")
inittab '-' character in process field
1,347,271,313,000
On my Debian server, I have no network shares (NFS, SMB, ...). I am trying to optimize and simplify my boot process. Is it OK to remove the following init scripts? /etc/rcS.d/S12mountnfs.sh /etc/rcS.d/S13mountnfs-bootclean.sh AFAICT, these are only needed, when NFS is to be mounted. However, I am not sure what purpose the mountnfs-bootclean.sh script has. Anyway, Is it safe to remove both these scripts, i.e.: chkconfig mountnfs-bootclean.sh off chkconfig mountnfs.sh off
You won't really optimize anything by removing these scripts. The time they take is negligible. The *-bootclean.sh scripts clean up files that must or should not survive a reboot: files in /var/run, /var/lock, /tmp, etc. In Debian with SysVinit, there are three such scripts: checkroot-bootclean.sh runs just after the root filesystem is mounted (which can remove spurious files created under directories that will soon become mount points, such as /run and potentially /tmp) mountall-bootclean.sh runs after local filesystems have been mounted (including e.g. a local separate /tmp or /var — or tmpfs filesystems, but there's nothing to clean on these) mountnfs-bootclean.sh runs after remote filesystems have been mounted (including e.g. /var over NFS). Disabling mountnfs.sh and mountnfs-bootclean.sh will not harm your system. However, to determine that, you need to study them carefully. Furthermore, this only applies under the assumption that you will never ever put an NFS filesystem in your fstab. If you know that this is true, then I would very much like you to imbue me with your divination abilities. If you merely believe that this is true, then you need to take into account the risk that your belief proves unfounded at some point. Every default that you change in the distribution makes your system different, so part of the documentation no longer applies, the testing that others have conducted may no longer apply, the support that you might get could be invalidated, etc. Any change to a default setting is inherently an added complication, and thus should only be performed if there is an actual benefit to be derived from it. Your assertion that removing these scripts will simplify your boot process is false, because you did not take this into account.
Removing unused init scripts
1,347,271,313,000
Are there any standards for aliasing sudo /etc/init.d/? I'm sure many people have considered cutting down these 17 characters to just 2 or so.
On Linux with SysVinit (the traditional init implementation), the service command is a shell script that calls a script in /etc/init.d. sudo service wibble restart service also knows to look for Upstart jobs if available. Upstart also comes with start, stop, reload and restart commands. sudo restart wibble I recommend keeping sudo to remind you that this is something performed as root.
Aliases for 'sudo /etc/init.d/'
1,347,271,313,000
I'm using apache2 and postgres running on Ubuntu Server 10.04. I have removed the startup scripts for both of these apps and I'm using supervisor to monitor and control them. The problem I have run into is that both of these need directories in /var/run (with the correct permissions for the users they run under) for pid files. How do I create these during startup as they need to be created as root and then chown'd to the correct user? Edit It seems the best way to so this is to creat the directories with custom init scripts. As I have no shell scripting skills at all how do I go about this?
In reply to this comment: There are currently no startup scripts for the servcies. The supervisor daemon is started by the init.d scripts and then the other services are started by this service, which should not run as root. If your supervisor is started from init.d script, then just create another init.d script with the preferences to be run before the supervisor starts ( how you achieve this is totally dependent on your flavor of **IX ). In its start method create needed directories with required permissions. In its stop method tear those directories down.
Create directory in /var/run/ at startup
1,347,271,313,000
I know that rc*.d directories are used at startup, or reboot, or so on time, for starting or stopping programs. Can anybody explain me what's the difference between the rc*.d folders placed under the /etc/ path and the other placed under the /etc/rc.d/ path. Also, what's the difference between /etc/init.d and /etc/rc.d/init.d? Thanks. N.B. I'm running CentOS 6.2.
Nothing. Different Linux distributions, and the LSB, had different standards, so both are present on CentOS to make it easier to run software from different versions. One is just a symbolic link to the other. http://www.centos.org/docs/5/html/5.1/Installation_Guide/s2-boot-init-shutdown-init.html gives details on the boot process, but ultimately all the init scripts are almost-but-not-completely identical on the different Linux systems.
What's the difference between /etc/rc.d/rc*.d and /etc/rc*.d
1,347,271,313,000
I just have a simple question but scouring the search engines I have not found any explanation of what the - (hyphen) in the chkconfig runlevel actually stands for within the init script file. For example in /etc/init.d/mysqld the first few lines are like this: #!/bin/bash # # mysqld This shell script takes care of starting and stopping # the MySQL subsystem (mysqld). # # chkconfig: - 64 36 If anyone could provide me a link explaining this that would be awesome.
The hyphen (-) found in an init script: #!/bin/sh # # chkconfig: - 24 73 means that the service should not be started in any run levels by default, only stopped. It replaces a list of run levels (e.g. 345) as shown below: #!/bin/sh # # chkconfig: 345 24 73 Therefore if you use: chkconfig --add <script> then no start links will be created in any of the init directories. $ ll rc*.d/*script* lrwxrwxrwx. 1 root root 17 Apr 24 2014 rc0.d/K73script -> ../init.d/script lrwxrwxrwx. 1 root root 17 Apr 24 2014 rc1.d/K73script -> ../init.d/script lrwxrwxrwx. 1 root root 17 Apr 24 2014 rc2.d/K73script -> ../init.d/script lrwxrwxrwx. 1 root root 17 Apr 24 2014 rc3.d/K73script -> ../init.d/script lrwxrwxrwx. 1 root root 17 Apr 24 2014 rc4.d/K73script -> ../init.d/script lrwxrwxrwx. 1 root root 17 Apr 24 2014 rc5.d/K73script -> ../init.d/script lrwxrwxrwx. 1 root root 17 Apr 24 2014 rc6.d/K73script -> ../init.d/script Notice only the Kill scripts links exist (K73script). References: A reference to this can be found on softpanorama.org: The first line tells chkconfig what runlevels the service should be started in by default, as well as the start and stop priority levels. If the service should not, by default, be started in any runlevels, a - should be used in place of the runlevels list.
What does the hyphen mean in chkconfig run level in an /etc/init.d script?
1,347,271,313,000
Is there some tool that displays all available init scripts (on Debian), short of one having to remember a location like /etc/init.d, not to mention that not everything in there is an init script?
The chkconfig utility can do this. Unlike RHEL or SLES, it does not come installed by default in Debian, but it is a good end-user tool for sysvinit configuration. To list all sysvinit services: chkconfig --list
Displaying all sysvinit init scripts
1,426,114,625,000
My script is not running on boot in a vagrant box under Ubuntu. My script looks like this - #!/bin/bash # /etc/init.d/mailcatcher ### BEGIN INIT INFO # Provides: scriptname # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start daemon at boot time # Description: Enable service provided by daemon. ### END INIT INFO mailcatcher --http-ip 192.168.50.10 My permissions on the file look like this - -rwxr-xr-x 1 root root 352 Apr 30 09:59 mailcatcher.sh I run the command - sudo update-rc.d "mailcatcher.sh" defaults If I run the script manually, it works and starts mailcatcher. If I reboot the computer, the mailcatcher daemon does not start. Am I missing something?
And now for the Ubuntu answers. This is an Ubuntu Linux question, and version 15 is now released. The Ubuntu world now has systemd. But even before version 15 the Ubuntu world had upstart. There really isn't a reason to write System 5 rc scripts; and there is certainly no good reason for starting from there. Both upstart and systemd do all of the "service controls". All that you need to do is describe the service. systemd A systemd service unit, to be placed in /etc/systemd/system/mailcatcher.service, is [Unit] Description=Ruby MailCatcher Documentation=http://mailcatcher.me/ [Service] # Ubuntu/Debian convention: EnvironmentFile=-/etc/default/mailcatcher Type=simple ExecStart=/usr/bin/mailcatcher --foreground --http-ip 192.168.50.10 [Install] WantedBy=multi-user.target This automatically gets one all of the systemd controls, such as: systemctl enable mailcatcher.service to set the service to be auto-started at boot. systemctl preset mailcatcher.service to set the service to be auto-started at boot, if the local policy permits it. systemctl start mailcatcher.service to start the service manually. systemctl status mailcatcher.service to see the service status. upstart Upstart is similar, and modifying Fideloper LLC's upstart job file to this question gives this for /etc/init/mailcatcher.conf: description "Mailcatcher" start on runlevel [2345] stop on runlevel [!2345] respawn exec /usr/bin/mailcatcher --foreground --http-ip=192.168.50.10 This automatically gets one all of the upstart controls, such as: initctl start mailcatcher to start the service manually. initctl status mailcatcher to see the service status. Bonus daemontools section For kicks, for the entertainment of any daemontools-family-using people who reach this via a WWW search, and to demonstrate another reason why not to begin at System 5 rc scripts, I ran that systemd service unit through the nosh toolset's convert-systemd-units command to produce the following daemontools-family run script: #!/bin/nosh #Run file generated from ./mailcatcher.service #Ruby MailCatcher chdir / read-conf --oknofile /etc/default/mailcatcher /usr/bin/mailcatcher --foreground --http-ip 192.168.50.10 Actually, the convert-systemd-units command generates a whole nosh service bundle directory. With that directory, which specifies dependency and ordering information, installed as /var/sv/mailcatcher in a system with the nosh service-manager one gets all of the nosh controls, such as: system-control enable mailcatcher.service to set the service to be auto-started at boot. system-control start mailcatcher.service to start the service manually. system-control status mailcatcher.service to see the service status. system-control preset mailcatcher.service to set the service to be auto-started at boot, if the local configuration (systemd-style presets or /etc/rc.conf{,.local}) permits it. Don't even begin with System 5 rc files. Look at this template used by SaltStack for System 5 rc scripts. Even with the SaltStack parameterization eliminated that is 59 lines of shell script code, most of which is generic boilerplate that you'd be having to re-invent and re-write. Again. And Celada has already pointed out where you've re-invented it badly. The systemd unit file is 11 lines long. The upstart job file is 8 lines. The nosh run script is 6. And they do all of the start/stop/status mechanics for you. Don't start with System V rc, especially not on Ubuntu Linux. Further reading Setting Up Mailcatcher. 2014-10-21. Servers for Hackers. Fideloper LLC. James Hunt and Clint Byrum (2014). "Utilities". Upstart Cookbook. Jonathan de Boyne Pollard (2014). A side-by-side look at run scripts and service units.. Frequently Given Answers.
init.d script not being run on boot
1,426,114,625,000
I'm trying to track down some quirkiness with a Java application that misbehaves when launched via a startup script in /etc/init.d , but runs fine when you open a GUI terminal window and run it through /etc/init.d/myapp start. (The quirkiness involves a portion of the app that does some hacky handwaving with X.) Since the app runs fine when launched via a terminal window, I'm looking at how it's launched before I dive into (admittedly delicate and not my) source code. The answer at this post gave me a clue that the Gnome terminal is running inside a window manager, which is somehow affecting (in a good way) the environment of the application I launch through a bash script. I was able to verify that launching the script through a tty terminal (ctrl-alt-f1 or via ssh) gives the same behavior as launching on startup. My main question: What can I do to start this application when the computer starts, but have it act like it's been started under X? We've gone the script route up 'til now because it also needs to start a Java VM with certain parameters. The follow up question (strictly to enhance my understanding): What is going on under the hood to make a script act differently when it's launched via something running in a window manager? Google has not enlightened me on this.
If your application needs an X server for some weird reason but doesn't do anything useful with it, give it a virtual X server. This is commonly done to run web browsers in automated test suites for web applications — nobody's looking at the screen but the web browser won't run without one. Xvfb creates an X server that “displays” only to memory, not to anything viewable. It doesn't require any hardware or permissions. The easiest way to use it is via the Debian xvfb-run script. xvfb-run java MyWeirdApp If you don't have xvfb-run, get it from one of many copies on the web or from the Debian package.
How to make /etc/init.d script act like it's launched under X?
1,426,114,625,000
I'm currently exploring creating a startup script in the form of a system process located in the /etc/init.d/ on my Fedora 14 Linux installation. It sounds like the following two lines are bare minimum requirements? #!/bin/bash # chkconfig: 345 85 15 (however on this one I've seen different combos) What's the purpose of these lines? Is there a good resource that would help me understand how to better create these and other header lines for such a file?
Look at the docs file /usr/share/doc/initscripts-*/sysvinitfiles (On current F14, /usr/share/doc/initscripts-9.12.1/sysvinitfiles). There's further documentation here: http://fedoraproject.org/wiki/Packaging/SysVInitScript. The chkconfig line defines which runlevels the service will start in by default (if any), and where in the startup process they'll be ordered. # chkconfig: <startlevellist> <startpriority> <endpriority> Required. <startlevellist> is a list of levels in which the service should be started by default. <startpriority> and <endpriority> are priority numbers. For example: # chkconfig: 2345 20 80 And, note that this all becomes obsolete with Fedora 15 and systemd.
Are certain parts of startup scripts necessary or just good practice?
1,426,114,625,000
To ask my question, I must first clarify the context. Every init script in /etc/init.d (on RedHat and Centos distros) is prepared to be managed with the chkconfig command-line tool utility. This tool manages the symlinks in /etc/rc[0-6].d, understand runlevels and permit to add and remove init scripts from the set that is meant to run for every runlevel. (see man chkconfig). NOTE: it does not start nor stop the services / daemons but it permit a simpler management of what is "on" and what is "off" in every runlevel. According to man, to achieve this, every init script in /etc/init.d have to contain exactly two directives on a commended line (chkconfig: and description:, see manpage ) or a LSB-style init stanza. But let put aside for a moment this LSB-tyles stanzas (which have been introduced relatively recently) and are much more descriptive than the original chkconfig "format" (this topic can be good for other questions). Out of curiosity, I have run on my RedHat boxes (5.2 & 6.1) this command to examine the init scripts: find /etc/init.d/ -ls -execdir head -n20 {} \; and I have see other (possibly undocumented) directives: # processname: # pidfile: # config: # Author: These are in the comment lines and look the same as the official directives (chkconfig: and description:). Does anyone know if these are chkconfig directives or they are only some nice formatted comments? If these are directive too what do they mean? There are some reference? I wasn't able to find any.
The documentation for these directives is in /usr/share/doc/initscripts-*/sysvinitfiles. Except for "Author", which is non-standard.
What are the chkconfig directives (classic style) into init.d scripts?
1,426,114,625,000
I am trying to run agetty in a runit based linux system, but I have the following problem sh: cannot set terminal process group (136) Inappropriate ioctl for device sh: no job control in this shell I have no clue about this error, do you have some ideas The script for running agetty is #!/bin/sh exec /sbin/agetty 38400 tty1 linux --noclear Any help will be good.
Use setsid as follows. #!/bin/sh exec setsid /sbin/agetty 38400 tty1 linux --noclear The setsid wrapper will start agetty as a session leader (see this answer), allowing it to bind to tty1. You can see the different behavior from the following example ps. # ps xao pid,ppid,sid,tty,cmd [...] 150 1 150 ? runsvdir 154 150 155 ? runsv agetty-3 157 154 157 tty3 -bash 152 150 152 ? runsv agetty-4 156 152 152 ? -bash [...] The agetty-3 service used setsid, whereas agetty-4 did not. Therefore, the shell on tty3 is session leader and bound to its tty. The shell on tty4 is in the same session of its supervisor and not bound (? in tty column).
Error trying to run agetty in a runit based linux installation
1,426,114,625,000
Here is my rc.local #!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. /bin/echo 12 > /sys/class/backlight/acpi_video0/brightness /bin/echo disable > /proc/acpi/ibm/bluetooth # Samsung at home /usr/bin/xrandr --newmode "1680x1050_60.00" 146.25 1680 1784 1960 2240 1050 1053 1059 1089 -hsync +vsync /usr/bin/xrandr --addmode VGA1 1680x1050_60.00 /usr/bin/xrandr --output VGA1 --mode 1680x1050_60.00 exit 0 whose permission is -rwxr-xr-x. The first command works, I can set the brightness of my laptop's monitor. The following script is to disable bluetooth and to set resolution of my external monitor. Only the first command is correctly executed, not the others. I know that rc.local stops running when a command fails. However, I've tried to run it manually /bin/sh /etc/rc.local Everything seems to work correctly, the bluetooth is disabled and the resolution is set without problem. I've also tried to run the first command in terminal /bin/echo 12 > /sys/class/backlight/acpi_video0/brightness echo $? It shows that the first command returns zero. So I don't understand why the system doesn't run all the commands in rc.local. I really need it, especially for the first 2 lines which need root permission.
/etc/rc.local is executed before the X server starts, so it has no access to any GUI features. The xrandr commands cannot have any effect. Put the xrandr commands in a different file, which runs when your GUI session starts. The file depends on your desktop environment.
Why doesn't rc.local run entirely
1,426,114,625,000
I have a init script which is poorly designed because it does not conform to the Linux Standard Base Specifications The following should have an exit code of 0 if running, and 3 if not running service foo status; echo $? However because of the way the script is designed, it always returns a 0. I can not fix the script without a significant rewrite (because service foo restart is dependent on service foo status). How could you work around the issue so that service foo status returns a 0 if running, and a 3 if not running? What I have so far: root@foo:/vagrant# service foo start root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l 1 root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l;echo $? 0 # <looks good so far root@foo:/vagrant# service foo stop root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l 0 root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l;echo $? 0 # <I need this to be a 3, not a 0
You are piping the grep output to wc and echo $? would return the exit code for wc and not grep. You could easily circumvent the problem by using the -q option for grep: /etc/init.d/foo status | /bin/grep -q "up and running"; echo $? If the desired string is not found, grep would return with a non-zero exit code. EDIT: As suggested by mr.spuratic, you could say: /etc/init.d/foo status | /bin/grep -q "up and running" || (exit 3); echo $? in order to return with an exit code of 3 if the string is not found. man grep would tell: -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. (-q is specified by POSIX.)
How to trick an init script into returning 0
1,426,114,625,000
I'm trying to write a cron job script that will check if my services are running and restart them if they aren't so I don't have to do it manually. Now, I've looked up online how to check the status of a service in a bash script, and have found basically the following, with a few variations: ps auxw | grep <service_name> | grep -v grep if [[ $? != 0 ]]; then /etc/init.d/<service_name> start fi I did some thinking and thought it might be a bit less hacky and more of a way of using the init script's general functionality to check it this way: /etc/init.d/<service_name> status if [[ $? != 0 ]]; then /etc/init.d/<service_name> start fi Please correct me if I'm wrong, but wouldn't this always work? Is this a property of init scripts in general, that they return that exit code? Thanks in advance. :)
Not 100% of the time. However, it's a very good yardstick. CFEngine 3 uses this in "services promises" to check if services are running. If the exit code of /etc/init.d/<servicename> status is zero, it assumes the service is running. I have just run into BitBucket's noncompliance with this convention: /etc/init.d/atlbitbucket status returns 0 even when it's not running. However, I would consider this to be undesirable behavior (a bug) in the init script, that it doesn't follow the convention. Found a reference for it; the Linux Standard Base Specification states: If the status action is requested, the init script will return the following exit status codes. 0 program is running or service is OK 1 program is dead and /var/run pid file exists 2 program is dead and /var/lock lock file exists 3 program is not running 4 program or service status is unknown 5-99 reserved for future LSB use 100-149 reserved for distribution use 150-199 reserved for application use 200-254 reserved So yes, compliant applications can be counted upon to behave in this fashion.
Does an init script always return a proper exit code when running status?
1,426,114,625,000
I am experiencing strange behavior with LSB Init Scripts in Debian Wheezy. I can demonstrate the problem on following example: The script /etc/init.d/resolvconf starts in S and stops in runlevels 0 and 6. # Default-Start: S # Default-Stop: 0 6 And indeed, when I use chkconfig resolvconf on to turn the script on, I see that symlinks have been created in respective runlevel directories: $ ls /etc/rc?.d/*resolvconf /etc/rc0.d/K02resolvconf /etc/rc6.d/K02resolvconf /etc/rcS.d/S13resolvconf When I turn the script off with chkconfig resolvconf off, the symlinks disappear. So far so good. Now, I have decided I don't want the script to start in S (I am going to start it manually), but I still want it to stop in runlevels 0 and 6. I change default start accordingly: # Default-Start: # Default-Stop: 0 6 and turn the script on chkconfig resolvconf on. And nothing happens. $ ls /etc/rc?.d/*resolvconf ls: cannot access /etc/rc?.d/*resolvconf: No such file or directory no symlinks have been created, and the script does not stop in runlevels 0 and 6. What is happening here? How can I have a script only run (stop) in runlevels 0 and 6, without starting in S ? UPDATE as suggested by @Rui F Ribeiro, I have completely removed the # Default-Start: line. Now when I run chkconfig resolvconf on, I get following errors: insserv: Script resolvconf is broken: incomplete LSB comment. insserv: missing `Default-Start:' entry: please add even if empty. insserv: Default-Start undefined, assuming empty start runlevel(s) for script `resolvconf' the symlinks are created, though. $ ls /etc/rc?.d/*resolvconf /etc/rc0.d/K02resolvconf /etc/rc6.d/K02resolvconf But why do I get the errors?
chkconfig only reads the "Default-Start" lines when calculating the runlevels for scripts. It counts the number of runlevels and only calls insserv if at least one runlevel is requested in "Default-Start"... Workarounds which avoid this behaviour include: enabling services with chkconfig -a; disabling services with chkconfig -d; using insserv directly, insserv service to enable service, insserv -r service to remove it.
confusing behavior of LSB Init Scripts in Debian
1,426,114,625,000
I have writen my own initscript /etc/init.d/myscript. I can start and stop my script with the service command service myscript start service myscript stop When I type service <TAB>, bash_completion displays all my initscripts from /etc/init.d/, including myscript. But when I type service myscript <TAB> nothing happens. I would like bash_completion to offer me start, stop as with other initscripts. For example, bash_completion works for service cups <TAB>, but I don't know where this is defined. There is no /usr/share/bash-completion/completions/cups or /etc/bash_completion.d/cups. So where does service get the info from? Where should I add my script info?
On older versions of bash-completion, like the one available for CentOS on the EPEL repository, there are individual scripts for sysvinit services in /usr/share/bash-completion/. In this case you may want to add additional scripts there based on an example like the cups completion. On newer systems, like my Fedora 19, bash-completion ships with the _service() and _services() functions in the main /usr/share/bash-completion/bash-completion script, it provides the start and stop actions by default for any installed service. It should work out of the box. If you also want to support more actions, add an Usage action like this: *) echo $"Usage: $0 {start|stop|status|restart|reload|force-reload}" The script will parse this string and complete the status, restart, and so on. This assumes that you are using a case statement like this to manage the action argumment: case $1 in start) [...] ;; stop) [...] ;; status) [...] ;; *) echo $"Usage: $0 {start|stop|status}" esac
bash_completion for initscripts
1,426,114,625,000
Background: I use Debian Lenny on an embedded device uname -a Linux device 3.4.0 #83 Sun May 26 17:07:14 CEST 2013 armv4l GNU/Linux I have a C code (say my_C_program) that calls a board specific binary file (via system("spictl someparameters") ) called spictl to use SPI interface user:~# ls -al /usr/local/bin/spictl lrwxrwxrwx 1 root staff 24 Jun 9 2011 spiflashctl -> /initrd/sbin/spiflashctl if I run my code (my_C_program) from the command line user:~# /user/sbin/my_C_program the spictl is executed without problem and outputs data from the SPI interface. Problem: I need the program to be run when the board is powered. Therefore, I add /user/sbin/my_C_program line before the exit 0 at/etc/rc.local. When the board is powered, the my_C_program is executed and spictl is executed but the SPI interface does not output any data. I tried to run the program via /etc/init.d/ script on this link. The script works fine and it executes the my_C_program, the program executes the spictl successfully (as system() return value says), but the SPI interface does not output any data! ls -l /usr/sbin/my_C_program -rwxrwxrwx 1 root root 61713 Jun 28 2013 /usr/sbin/my_C_program top shows that the program is run as root PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1095 root 20 0 2524 1140 924 R 4.2 1.8 0:00.35 top 1033 root RT 0 35092 34m 1852 S 3.0 56.5 0:14.06 node Question if I execute the my_C_program on terminal, the program calls the spictl (via system(spictl someparameters)) and it is executed without any problem. But if I run my_C_program through /etc/rc.local or /etc/init.d script, then spictl does not work as it supposed to be. I suspect that it has something to do with the root privilege. When I execute the program on the terminal (as root) all works fine. But I guess /etc/rc.local and /etc/init.d somehow runs the program with a lower privilege. I could not really solve the difference between executing a command from the terminal as root or executing the program via /etc/rc.local or /etc/init.d/ script. If you also think that it is a privilege problem, could you please explain how can I ensure that init.d script or rc.local would run the program with the highest privilege. Or what could be the issue? Please note that the problem/question is not SPI related. P.S. in order not to have unnecessary conversation like "oh Debian lenny is too old, you should use wheezy etc.", the board has armv4l processor and as the producer says it does not support wheezy because of some processor instructions.
You're C executable probably requires some environment variables to be set to function. For example the env. variable $PATH or $LD_LIBRARY_PATH. There also other variables such as $HOME which won't be set until a user has logged in. This last one might be necessary for your app to access config files and/or log files, for example.
why do I have two different results if I run a program through terminal(as root) or /etc/init.d(or /etc/rc.local)
1,426,114,625,000
I am manually tweaking Debian init scripts in order to optimize the boot time of an embedded device. So far I reduced it by half just with the "low hanging fruits" ie. the smaller scripts that are easy to understand. Now I am left with a few init scripts that take about 20s to run in total. Based on the experience from the other scripts, I can gain another 5 to 10 seconds here. The problem is those scripts are a bit too hard for me to understand because they source several helper scripts from /lib/init/ which are difficult to follow (mount-functions.sh being the first culprit). In order to make those remaining scripts easier to understand so that I can optimize them, I'd like some way to "pre-process" those init scripts so that whenever they source a file it gets inlined in the script itself (recursively of course), and remove the unused functions to unclutter the code. Is there a tool for this?
You could do something like this. I've only lightly tested it but I think the general concept is sound. Example Say you have the following directory of files: $ ls -l total 16 -rwxrwxr-x 1 saml saml 268 Oct 4 17:44 expander.bash -rw-rw-r-- 1 saml saml 18 Oct 4 16:49 src_1.bash -rw-rw-r-- 1 saml saml 20 Oct 4 16:50 src_2.bash -rwxrwxr-x 1 saml saml 119 Oct 4 16:49 top.bash The top.bash file looks like this: $ cat top.bash #!/bin/bash echo "1" echo "2" echo "3" echo "4" . src_1.bash echo "15" echo "16" . src_2.bash echo "27" echo "28" You could use the following script, expander.bash to "expand" top.bash: #!/bin/bash while read -r line; do if echo "$line" | grep -q '\. .*'; then file=$(echo "$line" | sed 's/\. //') echo "### below sourced from: $file" cat $file echo "### above sourced from: $file" continue fi printf "%s\n" "$line" done < top.bash Example Run $ ./expander.bash #!/bin/bash echo "1" echo "2" echo "3" echo "4" ### below sourced from: src_1.bash echo "6" echo "7" ### above sourced from: src_1.bash echo "15" echo "16" ### below sourced from: src_2.bash echo "17" echo "18" ### above sourced from: src_2.bash echo "27" echo "28" Potential Enhancements? For one I used grep and sed, those could be swapped out to make it a more pure Bash solution. I didn't take the time to do this, since this is a rough prototype. The second area that will most likely need attention is the scripts ability to figure out that a sourcing of another file is occurring. The pattern that detects this will likely need to be "tweaked" based on your situation.
Flatten shell script (include sourced scripts) and remove unused functions
1,426,114,625,000
I want to create a bootup script that runs before the root filesystem / has been mounted as I want to use dm-cache to cache it. The script is supposed to contain cache setup commands. Where would I need to put such a script and what format does it need to have? I cannot find any useful documentation by googling. Running Fedora 17, Kernel 3.9.10.
Going by the instructions on the dm-cache github, to create a cache you need the kernel modules dm_mod and dm_cache loaded (assuming you already have a patched kernel) Also you will need to access the dmsetup executable and presumably you want /dev to be populated so you can access the device on which you will create the cache. As cjm already mentioned, to do this you will need to modify your initramfs, which is a file system that is loaded into memory before the hard disk is mounted. luckily, dmsetup is already installed on the initramfs (This should always be the case, as it is needed for volume management; But to check use "lsinitramfs /initrd.img | grep dmsetup") This leaves two things things which you will have to add to your initramfs: the two modules and the script to create the cache. For the modules, simply edit either /usr/share/initramfs-tools/modules or /etc/initramfs-tools/modules Place your boot script in either /usr/share/initramfs-tools/local-premount or /etc/initramfs-tools/local-premount. Putting it in the local-premount subdirectory will ensure that the modules have been loaded and /dev is populated, but / has not been mounted yet. The script can be a normal sh script. Use the #!/bin/sh shebang and don't forget to make it executable. I assume you know how to write it yourself (otherwise, please provide more information) run update-initramfs -u to apply the changes, and you should be set. Make sure you have an older kernel remaining to boot into if something goes wrong. read 'man initramfs-tools' for general instructions on how to use initramfs-tools Using dracut: dracut uses a modular system to manage its bootup process. similarly to initramfs-tools, it possesses a hook called pre-mount, which you will want to use. To install your script, you will need to define a module which uses this hook: mkdir /usr/lib/dracut/modules.d/40dm-cache now edit the file /usr/lib/dracut/modules.d/40dm-cache/module-setup.sh #!/bin/bash # -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*- # ex: ts=8 sw=4 sts=4 et filetype=sh check() { return 0 } depends() { return 0 } install() { inst_hook pre-mount 91 "$moddir/dm-cache.sh" } installkernel() { instmods dm_mod instmods dm_cache } and /usr/lib/dracut/modules.d/40dm-cache/dm-cache.sh #!/bin/sh # -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*- # ex: ts=8 sw=4 sts=4 et filetype=sh modprobe dm_mod modprobe dm_cache ***here you insert your caching code. As before, dmsetup should be available at /sbin/dmsetup*** if you let check() return 255 instead of 0, the module will be loaded only if specified in dracut's config file (by returning 0, it will be loaded unconditionally) Now to update the initrd: dracut --force a dracut reference guide: https://www.kernel.org/pub/linux/utils/boot/dracut/dracut.html
How to write a pre-mount startup script?
1,426,114,625,000
I tried to display the list of startup scripts for the current runlevel at bootup. I wrote the following code. rl=`runlevel | cut -d " " -f2` ls /etc/rc.d/rc$rl.d/S* | cut -d "/" -f5 sleep 10 It's working if I put this code in rc.local file. But it's not working if I put it in rc file or in a separate script file abc in /etc/init.d and by creating softlinks in runlevel directories. But simple commands like follows are able to run in all the methods. ls /etc/init.d Do some commands like runlevel or piping won't work unless some of the scripts have started? Or is there something else? And if I put my code in rc file, my code runs before and after reboot. So what's the difference between rc, rc.local and rc.sysinit files? Where exactly I need to edit those files? Also I can find S99local -> softlink for rc.local in 2, 3, 4 and 5 runlevels. Does it mean that rc.local won't run on runlevel 1?
rc is typically not used by Linux distributions but is used in BSD rc.local is used to be able to execute additional commands during the startup without having to add symlinks. rc.sysinit seems to be Red Hat specific and is executed very early in the process. It is executed as one of the first scripts while rc.local is executed later. Also I can find S99local -> softlink for rc.local in 2,3,4 and 5 runlevels. Does it mean that rc.local won't run on runlevel 1? Correct, that means that S99local which is a symlink to /etc/rc.local will be one of the last scripts executed when entering runlevels 2, 3, 4 and 5. It won't get executed for runlevel 1 as 1 is the single user runlevel, typically used for rescue/maintenance work.
What is the difference between rc, rc.local and rc.sysinit?
1,426,114,625,000
I have an authoritative DNS daemon in my test DNS setup which is responsible to provide host IP at best choice. This daemon/process can run by setting some capabilities using setcap and then a development user can start or stop this without becoming the root user or using sudo. But while booting up the box, this daemon/process again appears as running as root in ps output. Can I start/stop this process with minimal capability/privileges from a non-root user? Then, at the bootup, I also don't want to see this running as the root user. Is there any mechanism in init scripts to run the given process with non zero uid?
You could use su in your startup scripts: su -s /bin/sh -c '/usr/bin/somedaemon' someuser Another solution would be to start the daemon using cron.
possibility of running daemons with under privileged users during bootup
1,426,114,625,000
I am just going through the service-list of a server (CentOS 5) - the question will probably apply to other RedHat, Fedora, ... versions, too. Note that my servers normally run in runlevel 3 (no GUI server processes started). I stumbled across two services: readahead_early readhahead_later These two services get their configuration from /etc/sysconfig/readahead.d The purpose of these services seems to be to preload certain files into cache-memory. Browsing through the config-files (left at the default contents) I see mostly X11-related files and some libraries. What is the deeper sense of these processes? AFAIK every file will go into cache-memory after the first read-access. Why should I preload - and why should I preload all these unneeded files? IMHO this is a useless waste of read-bandwidth during start-up of the operating system. Update I found that these readaheads will only cache the first inode-entries for the files listed (via the fstat system call). So it just speeds up finding these files... Update 2012-10-02 The question boils down to: Can I safely disable these services on a server, or am I missing something important here? I Updated the header of the question accordingly, since the given answers don`t hit the mark yet.
The idea is to load these files into cache before they're needed, so that there is no need to wait for them when X is trying to start. Obviously, there isn't much point in doing this for files that aren't actually needed in the system's day-to-day operation, so for example caching the X server itself is counterproductive in your case, yes; however, you might be surprised at what can get pulled in sometimes: it's quite possible that some programs your server runs actually do pull in X11 libraries, perhaps via Cairo, so don't be too hasty in dismissing this as useless! It might be better if the system periodically traced itself at startup to figure out what to precache (and when); Windows does something of the sort. (It also does this on a per-exe basis for process startup; I've actually seen the kernel pulling stuff into cache early after consulting its records about a new process's executable!) Again, this is all about reducing the time spent waiting for things to come in from storage. Edit: This is, of course, not essential. Nothing will break if it doesn't happen (barring stupid bugs); startup timing will just be different.
Can readahead-services be safely disabled?
1,426,114,625,000
I'm not sure what the general methodology of daemonizing a script is. For example, I've searched online and if I was trying to write a python script that checked the time every second on my computer, all I could think of is using systemd to start it up and then in Python write the script within a never ending loop with a timer. This neither make much sense to me nor does it seem like a good way of daemonizing. All I would do with systemd is use it to run the script (and any script) at startup, so systemd itself doesn't seem very useful. I think I may be daemonizing my script wrong, so do you know what the better ways are to use systemd to turn a python script into a daemon process? Thanks
systemd is not a catch-all. It won't be the solution to every problem, however it does give you a lot of tools to help you solve problems. The usefulness of those tools comes down to how well you can use them. Let's look at a very basic service file check-time.service (note that I created this service file by hand, using other service files located in /usr/lib/systemd/system/ as references): [Unit] Description=Checks the time every second [Service] Type=simple ExecStart=/usr/bin/check-time.py The service file belongs in /usr/lib/systemd/system/ or /etc/systemd/system/ to be used by systemd Line By Line [*] The section headers. These just group together directives. You can find references to which directives belong where in the systemd man pages: [Unit] section [Service] section [Install] section Description A free-form string describing the unit. This is intended for use in UIs to show descriptive information along with the unit name. The description should contain a name that means something to the end user. "Apache2 Web Server" is a good example. Bad examples are "high-performance light-weight HTTP server" (too generic) or "Apache2" (too specific and meaningless for people who do not know Apache). type Configures the process start-up type for this service unit. One of simple, forking, oneshot, dbus, notify or idle. If set to simple (the default if neither Type= nor BusName=, but ExecStart= are specified), it is expected that the process configured with ExecStart= is the main process of the service. In this mode, if the process offers functionality to other processes on the system, its communication channels should be installed before the daemon is started up (e.g. sockets set up by systemd, via socket activation), as systemd will immediately proceed starting follow-up units. ExecStart Commands with their arguments that are executed when this service is started. The value is split into zero or more command lines according to the rules described below (see section "Command Lines" below). Summary This service file would simply run the command /usr/bin/check-time.py when started. If the command exits then it would be considered "dead", so long as it continues to run it is considered "Active". How useful is this service file? Well, not very. As it is the only thing it does is allow you to run the python script using systemctl start check-time.service instead of the normal full path, however there are a wealth of additional options that can be useful. Useful Options WantedBy If you want the service to start on boot, set WantedBy= your default target. Restart Determines when systemd should automatically restart a service, such as "always" or "on-failure" Literally hundreds of other options that include limiting hardware usage, which user to use to execute the process, setting environment variables, setting dependencies, and many more. systemd is useful for all the additional functionality it provides, not simply because it can wrap things.
What are ways of creating a daemon using systemd? [closed]
1,426,114,625,000
When I boot my system, I can see the boot messages on my physical console tty1. After my X server has started, I can switch back to tty1 with CTRLALT+F1, and still see the output on the console. There is no getty running, because I have commented out the following line in /etc/inittab: #1:2345:respawn:/sbin/getty 38400 tty1 However, I am not able to scroll back in the console, nothing works, and even enter does not do anything. I would like to scroll back, to see the earlier boot messages (output of init scripts, which I cannot see in dmesg) I am using Debian and SysVinit as my init
It's not possible and it has never been possible AFAIK. This is well explained in the Linux keyboard and console HOWTO: the console display history uses the video memory witch is flushed when you switch console. Upon changing virtual consoles, the screen content of the old VT is copied to kernel memory, and the screen content of the new VT is copied from kernel memory to video memory. Only the visible screen is copied, not all of video memory, so switching consoles means losing the scrollback information.
cannot scroll back in console (tty1)
1,426,114,625,000
At the top of files in /etc/init.d are comments like the following. ### BEGIN INIT INFO # Provides: ntp # Required-Start: $network $remote_fs $syslog # Required-Stop: $network $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 1 # Short-Description: Start NTP daemon ### END INIT INFO What is the program that parses those comments? I'm interested in seeing how it does it. Is it a script?
The LSB info is parsed by insserv on older Ubuntu and Debian systems, and by chkconfig on older Redhat and Fedora systems, and is now parsed by /usr/lib/systemd/system-generators/systemd-sysv-generator on systems using systemd. All of these are coded in C. The pre-systemd chkconfig sources in the above link are probably a good starting point.
What is it that parses the LSB information in init scripts?
1,426,114,625,000
On a system that uses SysV init run levels such as Centos 5, when the OS is booting, does it go straight to the run level defined in /etc/inittab? If I change my run level using the init command do the kill scripts for my current run level execute and then the start up scripts for the new run level execute? For example if I was at run level 3 and entered init 1, would the kill scripts in /etc/rc.d/rc3.d be executed and then upon entering run level 1 would the startup scripts in /etc/rc.d/rc1.d be run?
Yes, SysVinit goes straight to the chosen run-level on boot without looking at scripts in other levels. You can view the runlevel history using the runlevel command. On first boot, it will show the "previous" runlevel as 'N'. After a runlevel change it will show the previous and current runlevel. When switching runlevel, it first looks at the difference between them. Any services that are listed in the current level but not in the new one are first killed using the kill scripts, then any that are listed in the new level but not in the old one are run. Services that exist in both run levels are not touched. For example switching from runlevel 3 to 5 will usually result in a few things (like a display manager) being started, but nothing killed. Switching from 5 to 1 will result in quite a few things being killed, then maybe 1 (like a single user interface console manager) being run.
SysV init run levels
1,426,114,625,000
I've just started playing with Debian 6.0 (Squeeze) in a VPS environment, as a way to learn more about system administration. One thing I'd like to configure is a default packet filtering policy. (Permit new and established SSH inbound, permit rate limited ICMP inbound, drop everything else inbound, permit anything outbound, etc etc) I've determined how to build a policy which roughly meets my needs, however there doesn't seem to be an existing init script which specifies where iptables should load its policy from on startup. Is there a standard way to do this on Debian? I've seen various alternatives suggested, all of which seem to involve creating a shell script somewhere somewhere and invoking it in RC scripts, initscripts, /etc/network/interfaces... Is there no 'blessed' way to do this in Debian? It seems like a fairly glaring oversight.
There is no default standart way to setup a firewall in Debian, except maybe calling a script with a pre rule in the network configuration (/etc/network/interfaces) but there are many packages providing different ways to do it. For example the packages uruk and iptables-persistent provide very simple scripts to load and backup a very simple firewall.
Is there a standard way to configure what policy iptables loads on startup under Debian?
1,426,114,625,000
I want to have radvd (the IPv6 router advertisement daemon) run on startup on Fedora 13. However, the network interface that it will use must be up, otherwise the daemon won't start. If I run the daemon manually when the system is running everything works fine. However, I can't figure out how to tell the Fedora 13 init system "run radvd on boot but only after wlan0 is up". wlan0 is managed by NetworkManager and it would be nice if I could keep it that way. I tried enabling radvd on boot using the GUI system-config-services tool; then radvd tries to start in the boot process (after NetworkManager) but fails because wlan0 does not exist. I also tried changing ONBOOT=no to ONBOOT=yes in /etc/sysconfig/networking/devices/ifcfg-wlan0 but that also didn't help (I don't understand exactly how the configuration in /etc/sysconfig/networking/ interacts with NetworkManager). It seems to me that this kind of thing should be straightforward with Upstart but I can't find an Upstart event that tells me "a network interface is up".
I am not too familiar with Fedora, but I know network manager does have a built-in system to run scripts after an interface comes up. On Arch linux the scripts are located at /etc/NetworkManager/dispatcher.d You will need to create a script to say when the interface is up, do this, when the interface is down do this. In your case, start raddvd when the interface is up, and stop it when the interface is down. Arch Linux's wiki has a bit more info and an example script that should get your going just fine. https://wiki.archlinux.org/index.php/NetworkManager#Network_Services_with_NetworkManager_Dispatcher
Run daemon on startup in Fedora 13 after wireless interface is up
1,426,114,625,000
While learning the Network Teaming objective of the RHCE (RHEL7) exam I noticed that examples use DEVICETYPE directive in the ifcfg scripts for master and port interfaces. I knew there was TYPE directive that I've seen in other ifcfg scripts before. The question arisen was what's the difference between those two directives?
After checking man pages, initscripts (package owning ifcfg scripts) documentation in /usr/share/doc/initscripts-*/sysconfig.txt, initscripts mailing list, and several bugs from redhat's bug tracker the only thing I understood is that to avoid problems those two directives should not be used in the same ifcfg script. I then forwarded my question to Jiri Pirko, Network Teaming (libteam) project maintainer. Here is the reply I got from him: Well the reason [for using DEVICETYPE] was political, not technical. Using DEVICETYPE, you can simply install additional initscripts with the package (teamd). But that does not matter anymore because initscripts now directly support team, so you can use TYPE. Contrary to Jiri's answer I must note that according to my tests it still matters what directive is used on my system. Network teaming interface works with DEVICETYPE=Team directive, but doesn't work with TYPE=Team directive. My configuration: CentOS Linux release 7.0.1406 libteam-1.9-15.el7.x86_64 teamd-1.9-15.el7.x86_64 initscripts-9.49.17-1.el7.x86_64 An update from Jiri after I pointed that usage of DEVICETYPE over TYPE still matters for teaming interfaces: The support is added by following commit: https://git.fedorahosted.org/cgit/initscripts.git/commit/?id=3235be4a3da91bc91c698b318935240dbdf81aac If it is not in 7.0, I believe it will be in 7.1
What's the difference between TYPE and DEVICETYPE directives in ifcfg scripts?
1,426,114,625,000
I've written a simple init script to start and stop a Python script as a service. I have to be explicit about the version of Python I'm running, because this is on a CentOS 5 box with Python 2.4 & 2.6 installed (both via yum). Here's what I have so far: #!/bin/sh # chkconfig: 123456 90 10 workdir=/usr/local/bin/Foo start() { cd $workdir /usr/bin/python26 $workdir/Bar.py & echo "FooBar started." } stop() { pid=`ps -ef | grep '[p]ython26 /usr/local/bin/Foo/Bar.py' | awk '{ print $2 }'` echo $pid kill $pid sleep 2 echo "FooBar stopped." } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; *) echo "Usage: /etc/init.d/foobar {start|stop|restart}" exit 1 esac exit 0 So: 1) I want to be "smarter" about the filename and directory name management, and set some variables up to so that anything repeated later in the script (like workdir). My main problem is the grep statement, and I haven't figured out how to deal with the variables inside the grep. I'd love any suggestions of a more efficient way to do this. 2) I want to add "status" support to this init script and have it check to see if the Bar.py is running.
I may be missing something but I don't understand why you are fiddling with grep in the first place. That's what pgrep is for: #!/bin/sh # chkconfig: 123456 90 10 workdir=/usr/local/bin/Foo start() { cd $workdir /usr/bin/python26 $workdir/Bar.py & echo "FooBar started." } stop() { pid=`pgrep -f '/Bar.py$'` echo $pid kill $pid sleep 2 echo "FooBar stopped." } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; *) echo "Usage: /etc/init.d/foobar {start|stop|restart}" exit 1 esac exit 0 The pgrep command is designed to return the PIDs of processes whose name matches the pattern given. Since this is a python script, the actual process is something like: python /usr/local/bin/Bar.py Where the process name is python. So, we need to use pgrep's -f flag to match the entire name: -f, --full The pattern is normally only matched against the process name. When -f is set, the full command line is used. To ensure that this does not match things like fooBar.py, the pattern is /Bar.py$ so that it matches only the portion after the last / and at the end of the string ($). For future reference, you should never use ps | grep to get a PID. That will always return at least two lines, one for the running process and one for the grep you just launched: $ ps -ef | grep 'Bar.py' terdon 27209 2006 19 17:05 pts/9 00:00:00 python /usr/local/bin/Bar.py terdon 27254 1377 0 17:05 pts/6 00:00:00 grep --color Bar.py
Grepping a variable
1,426,114,625,000
I'm running a raspbian (based on debian). I want to change the priority of the init services so the very first script which is run by init is one made for me. How can I do it? On runlevel S I have 3 scripts with priortity 01: hostname.sh, fake-hwclock and mountkernfs.sh. If I just put my script on runlevel S with priority 01, it's not the first one to be executed. I have tried to change the priortiy of all these scripts to 02 using (for example in the case of mountkernfs.sh) sudo update-rc.d -f mountkernfs.sh remove sudo update-rc.d mountkernfs.sh start 02 S The first command effectively removes the script from /etc/rcS.d. The second command puts again mountkernfs.sh with priority 01. Any idea? Thank you!
The init scripts on /etc/init.d/ specify some information on it's LSB header, which in essence are just some lines at the beginning of the script. The field "Required-Start" of some script allows you to specify services that must be initialized before this script. insserv automatically add init scripts regarding LSB header. Therefore, to solve the problem: Name your script "X" using "Provides" field on LSB header. Add the runlevels where the script has to be started and stopped using "Default-Start" and "Default-Stop" fields respectively on LSB header. Set "X" to the field "Required-Start" on the LSB header of the scripts with priority 01: hostname.sh, fake-hwclock and mountkernfs.sh. Add the service using sudo insserv name_of_your_script_file (not the name you give to "Provides" field) This moves all the necessary script priorities of the involved scripts to match the dependencies. In my case: S01X.sh S02mountkernfs.sh S02hostname.sh S02fake-hwclock S03udev Source: http://wiki.debian.org/LSBInitScripts/DependencyBasedBoot .
Change init scripts priority
1,426,114,625,000
I have a bash script in crontab that runs @reboot: The script itself contains a wget command to pull and download a file from the internet When I run my script after signing in and opening the terminal it works and saves the files properly(html, png). But when I reboot my system it saves runs and saves as plain text files with no content. Solved --> I used the sleep function in crontab and it works!!! New to linux and code, so thanks for all the feedback! I'm going to explore the /etc/network/if-up.d/ options as well.
The issue is almost certainly that your @reboot cron job has started before your network interfaces have come up. This is, in general, a well-documented shortcoming of cron. It doesn't mean the @reboot facility is useless, it just means you need to understand how it works, and how to work around it when it fails - as it has in your case (probably :). There are at least 2 ways to do this: use sleep in your @reboot job to give the network more time to get up. Your crontab entry will look something like this: : @reboot sleep 10; /your/bash/script/as-it-is-now I suggested the value of 10 here to give the interface 10 seconds to come up; YMMV, so experiment with different values. following up on @confetti 's suggestion (and with thanks to @Celada), put your script in /etc/network/if-up.d. Following is a prototype that may be useful. Note that it only runs the first time your system comes up (like @reboot, and NOT each time the network interface is brought up): #!/bin/sh NWKSTATUS=/var/run/the-network-is-up # note that /var/run is a temp fs, and so a system shutdown # will effectively erase our flag file, 'the-network-is-up' case "$IFACE" in lo) # Exclude the loopback interface; we won't consider it # as it's not a true interface. We set the flag only # when a true network interface comes up exit 0 ;; *) ;; esac # if the flag file exists, we're done here # otherwise, we'll create it if [ -e $NWKSTATUS ]; then exit 0 else touch $NWKSTATUS fi # add your script here... So - put all of the above into a file (e.g. setnwkstatus.sh), then save it in the folder /etc/network/if-up.d/ and make it executable (i.e. sudo chmod /etc/network/if-up.d/setnwkstatus.sh )
wget saving files as emply plain text files on boot
1,426,114,625,000
i.e. Using something like IPython, re.pl, or somesuch as a login shell, instead of bash/ksh/etc. Using initscripts, etc. written in Python or some other scripting language, and making no use of shell scripts whatsoever Not having any POSIX-compatible command shell installed In other words I'm thinking of more a Windows-like approach, where the "CLI" is a REPL interface for a true scripting language (a la Powershell) that most programs are completely independent of. Is this feasible? How reliant are Linux ports of desktop programs like Firefox, or web services like Apache, on having a working POSIX shell? How about the Linux kernel itself?
I believe the Linux kernel does not depend on a POSIX shell, (though will look for the #! line when executing files). I suspect it is possible to have a working Linux system, but most software will expect mostly POSIX-compliance, and desktop software will typically expect most of LSB (Linux Standard Base) compatibility too. Many applications, such as Firefox, use (POSIX) shell wrappers to run, so these will not work without modification.
Is it possible to create a Linux environment without a traditional command shell?
1,387,757,805,000
I recently purchased a vps and I attempted to create a startup/restart script to start up my java program. I am running CentOS 6. The script works if I execute it manually with this command: service policyserver start But fails to run automatically, creates a file in the /tmp/test.log with the following error: Starting Policy Server: failed Here is the startup script inside /etc/init.d/ #!/bin/bash # #policyserver: Startup script for CamSpark Policy Server Application. # #chkconfig: 3 80 05 #description: Startup script for Cam Spark Policy Server Application. CAMSPARK_POLICY_HOME=/tools/camsparkserver/Policy; export CAMSPARK_POLICY_HOME start() { echo -n "Starting Policy Server: " $CAMSPARK_POLICY_HOME/Policy.sh start >> /tmp/test.log sleep 2 echo "done" } stop() { echo -n "Stopping Policy Server: " $CAMSPARK_POLICY_HOME/Policy.sh stop echo "done" } # See how we were called. case "$1" in start) start ;; stop) stop ;; restart) stop start ;; *) echo $"Usage: policyserver {start|stop|restart}" exit esac Here is the main script (can't move this script) #!/bin/bash # # chkconfig: 345 99 05 # description: Java deamon script # # A non-SUSE Linux start/stop script for Java daemons. # # Set this to your Java installation JAVA_HOME=/usr/java/latest scriptFile=$(readlink -fn $(type -p $0)) # the absolute, dereferenced path of this script file scriptDir=$(dirname $scriptFile) # absolute path of the script directory serviceNameLo="policyserver" # service name with the first letter in lowercase serviceName="PolicyServer" # service name serviceUser="root" # OS user name for the service serviceGroup="root" # OS group name for the service applDir="/tools/camsparkserver/Policy" # home directory of the service application serviceUserHome="/home/$serviceUser" # home directory of the service user serviceLogFile="/var/log/$serviceNameLo.log" # log file for StdOut/StdErr maxShutdownTime=15 # maximum number of seconds to wait for the daemon to terminate normally pidFile="/var/run/$serviceNameLo.pid" # name of PID file (PID = process ID number) javaCommand="java" # name of the Java launcher without the path javaExe="$javaCommand" # file name of the Java application launcher executable javaArgs="PolicyServer" # arguments for Java launcher javaCommandLine="$javaExe $javaArgs" # command line to start the Java service application javaCommandLineKeyword="PolicyServer" # a keyword that occurs on the commandline, used to detect an already running service process and to distinguish it from others # Makes the file $1 writable by the group $serviceGroup. function makeFileWritable { local filename="$1" touch $filename || return 1 chgrp $serviceGroup $filename || return 1 chmod g+w $filename || return 1 return 0; } # Returns 0 if the process with PID $1 is running. function checkProcessIsRunning { local pid="$1" if [ -z "$pid" -o "$pid" == " " ]; then return 1; fi if [ ! -e /proc/$pid ]; then return 1; fi return 0; } # Returns 0 if the process with PID $1 is our Java service process. function checkProcessIsOurService { local pid="$1" if [ "$(ps -p $pid --no-headers -o comm)" != "$javaCommand" ]; then return 1; fi grep -q --binary -F "$javaCommandLineKeyword" /proc/$pid/cmdline if [ $? -ne 0 ]; then return 1; fi return 0; } # Returns 0 when the service is running and sets the variable $pid to the PID. function getServicePID { if [ ! -f $pidFile ]; then return 1; fi pid="$(<$pidFile)" checkProcessIsRunning $pid || return 1 checkProcessIsOurService $pid || return 1 return 0; } function startServiceProcess { cd $applDir || return 1 rm -f $pidFile makeFileWritable $pidFile || return 1 makeFileWritable $serviceLogFile || return 1 cmd="nohup $javaCommandLine >>$serviceLogFile 2>&1 & echo \$! >$pidFile" # Don't forget to add -H so the HOME environment variable will be set correctly. sudo -u $serviceUser -H $SHELL -c "$cmd" || return 1 sleep 0.1 pid="$(<$pidFile)" if checkProcessIsRunning $pid; then :; else echo -ne "\n$serviceName start failed, see logfile." return 1 fi return 0; } function stopServiceProcess { kill $pid || return 1 for ((i=0; i<maxShutdownTime*10; i++)); do checkProcessIsRunning $pid if [ $? -ne 0 ]; then rm -f $pidFile return 0 fi sleep 0.1 done echo -e "\n$serviceName did not terminate within $maxShutdownTime seconds, sending SIGKILL..." kill -s KILL $pid || return 1 local killWaitTime=15 for ((i=0; i<killWaitTime*10; i++)); do checkProcessIsRunning $pid if [ $? -ne 0 ]; then rm -f $pidFile return 0 fi sleep 0.1 done echo "Error: $serviceName could not be stopped within $maxShutdownTime+$killWaitTime seconds!" return 1; } function startService { getServicePID if [ $? -eq 0 ]; then echo -n "$serviceName is already running"; RETVAL=0; return 0; fi echo -n "Starting $serviceName " startServiceProcess if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi echo "started PID=$pid" RETVAL=0 return 0; } function stopService { getServicePID if [ $? -ne 0 ]; then echo -n "$serviceName is not running"; RETVAL=0; echo ""; return 0; fi echo -n "Stopping $serviceName " stopServiceProcess if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi echo "stopped PID=$pid" RETVAL=0 return 0; } function checkServiceStatus { echo -n "Checking for $serviceName: " if getServicePID; then echo "running PID=$pid" RETVAL=0 else echo "stopped" RETVAL=3 fi return 0; } function main { RETVAL=0 case "$1" in start) # starts the Java program as a Linux service startService ;; stop) # stops the Java program service stopService ;; restart) # stops and restarts the service stopService && startService ;; status) # displays the service status checkServiceStatus ;; *) echo "Usage: $0 {start|stop|restart|status}" exit 1 ;; esac exit $RETVAL } main $1 Does anyone know what could be the problem? EDIT: ran one of the answers posted here. Here is what I get when I just run that command [root@camspark Policy]# service policyserver stop Stopping Policy Server: Stopping PolicyServer stopped PID=683 done [root@camspark Policy]# bash -x service policyserver start |& tee policyserver_startup.log + . /etc/init.d/functions ++ TEXTDOMAIN=initscripts ++ umask 022 ++ PATH=/sbin:/usr/sbin:/bin:/usr/bin ++ export PATH ++ '[' -z '' ']' ++ COLUMNS=80 ++ '[' -z '' ']' +++ /sbin/consoletype ++ CONSOLETYPE=pty ++ '[' -f /etc/sysconfig/i18n -a -z '' -a -z '' ']' ++ . /etc/profile.d/lang.sh ++ unset LANGSH_SOURCED ++ '[' -z '' ']' ++ '[' -f /etc/sysconfig/init ']' ++ . /etc/sysconfig/init +++ BOOTUP=color +++ RES_COL=60 +++ MOVE_TO_COL='echo -en \033[60G' +++ SETCOLOR_SUCCESS='echo -en \033[0;32m' +++ SETCOLOR_FAILURE='echo -en \033[0;31m' +++ SETCOLOR_WARNING='echo -en \033[0;33m' +++ SETCOLOR_NORMAL='echo -en \033[0;39m' +++ PROMPT=no +++ AUTOSWAP=no +++ ACTIVE_CONSOLES='/dev/tty[1-6]' +++ SINGLE=/sbin/sushell ++ '[' pty = serial ']' ++ __sed_discard_ignored_files='/\(~\|\.bak\|\.orig\|\.rpmnew\|\.rpmorig\|\.rpmsave\)$/d' ++ basename service + VERSION='service ver. 0.91' ++ basename service + USAGE='Usage: service < option > | --status-all | [ service_name [ command | --full-restart ] ]' + SERVICE= + SERVICEDIR=/etc/init.d + OPTIONS= + '[' 2 -eq 0 ']' + cd / + '[' 2 -gt 0 ']' + case "${1}" in + '[' -z '' -a 2 -eq 1 -a policyserver = --status-all ']' + '[' 2 -eq 2 -a start = --full-restart ']' + '[' -z '' ']' + SERVICE=policyserver + shift + '[' 1 -gt 0 ']' + case "${1}" in + '[' -z policyserver -a 1 -eq 1 -a start = --status-all ']' + '[' 1 -eq 2 -a '' = --full-restart ']' + '[' -z policyserver ']' + OPTIONS=' start' + shift + '[' 0 -gt 0 ']' + '[' -f /etc/init.d/policyserver ']' + env -i PATH=/sbin:/usr/sbin:/bin:/usr/bin TERM=xterm /etc/init.d/policyserver start Starting Policy Server: done [root@camspark Policy]# Here is what is inside that log file [root@camspark Policy]# head policyserver_startup.log + . /etc/init.d/functions ++ TEXTDOMAIN=initscripts ++ umask 022 ++ PATH=/sbin:/usr/sbin:/bin:/usr/bin ++ export PATH ++ '[' -z '' ']' ++ COLUMNS=80 ++ '[' -z '' ']' +++ /sbin/consoletype ++ CONSOLETYPE=pty [root@camspark Policy]#
You can debug an issue like this by running the start script in a more verbose manner. $ bash -x service policyserver start You might want to capture this output to a log file too. $ bash -x service policyserver start |& tee policyserver_startup.log You can then go through the log file and see which command is failing.
chkconfig bootup script failing, script runs good manually