output
stringlengths 9
26.3k
| input
stringlengths 26
29.8k
| instruction
stringlengths 14
159
|
---|---|---|
Use gpasswd instead.
gpasswd -d user groupIt also has option for adding user to group
gpasswd -a user group |
i have tor install on my raspberry.
*:/home/bitcoin $ cat /etc/group | grep debian-tor
debian-tor:x:116:bitcoin,root,piover can i add a user
sudo usermod -a -G debian-tor bitcoinbut how can i delete?
i wan't root and pi delete.
| Delete User in /etc/group |
You’re doing nothing wrong. The fact that your system has version 0.2.9.16 tells me that you’re running Debian 9, and Debian 9 only has version 0.2.9.16 of Tor. However, newer versions have been made available in the backports repositories, and you can install version 0.4.1.6 from there:
echo deb http://deb.debian.org/debian stretch-backports main | sudo tee /etc/apt/sources.list.d/stretch-backports.list
echo deb http://deb.debian.org/debian stretch-backports-sloppy main | sudo tee -a /etc/apt/sources.list.d/stretch-backports.list
sudo apt update
sudo apt -t stretch-backports install tor |
I run a tor node on debian. Nyx says that my version (0.2.9.16 (git-9ef571339967c1e5)) is obsolete.
But when I try to do apt update && apt upgrade, nothing happens, all packages seem up to date. And apt-cache showpkg tor only shows my current version and older ones.
What am I doing wrong? Why can't I update tor?
| Debian Tor Node - Can't update to newer version |
The way Torsocks works, it's prone to leakage (outbound traffic not through Tor) depending on what the application it's being used on does. Whonix is safer in this regard, as it uses two isolated environments, and the one you run your applications in has no Internet access except through Tor.
| I've read somewhere that Whonix OS will force all connections through Tor. And I also read about Torsocks who seem to do the same thing.
So what's the difference between them?
And which one is safer to use?
| Which is safer, Whonix gateway or Torsocks? [closed] |
HiddenServicePort 9998 127.0.0.1:9998 means that, in order to access it, you will need to browse to <hostname>:9998 in the Tor Browser.
If you just want the default HTTP port, you can use HiddenServicePort 80 127.0.0.1:9998 and you could add HTTPS with HiddenServicePort 443 127.0.0.1:9998.
|
I want to serve a website through tor, so that I don't have to pay a hosting service or provide my ip to the users.
I've followed the steps on Arch Wiki and torproject.org:
Step 0: Get a working Tor
$ yay -S tor
$ sudo systemctl enable --now tor.serviceStep 1: Get a web server working
Previous steps.
$ cd ~/code/go/stash-box
$ ./stash-box --host 127.0.0.1 --port 9998 &Step 2: Configure your Tor Onion Service
Added this lines to /etc/tor/torrc
HiddenServiceDir /var/lib/tor/media_wiki/
HiddenServicePort 9998 127.0.0.1:9998Step 3: Restart Tor and check that it worked
$ sudo systemctl restart torStep 4: Test that your Onion Service works
When I visit the address in /var/lib/tor/media_wiki/hostname with the Tor Browser I see an Unable to connect message.
What else do I need to do?
| How to set up onion service? |
The parameter you want to change is:
SocksPort 0.0.0.0:9150Usually this is located in torrc file.
|
i would like to change default tor port from 9050 to 9150.
Editing /etc/tor/torsocks5.conf i can see these:
TorPort 9050
so, changing to 9150, it should work, right? it doesnt.
> sudo vi /etc/tor/torsocks.conf> sudo cat /etc/tor/torsocks.conf | grep 9150TorPort 9150> sudo service tor reload
> sudo service tor restart
> sudo service tor status
● tor.service - Anonymizing overlay network for TCP (multi-instance-master)
Loaded: loaded (/lib/systemd/system/tor.service; enabled; vendor preset: disabled)
Active: active (exited) since Mon 2022-06-27 13:46:11 CEST; 7s ago
Process: 43748 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
Main PID: 43748 (code=exited, status=0/SUCCESS)
CPU: 2msJun 27 13:46:11 kali systemd[1]: Starting Anonymizing overlay network for TCP (multi-instance-master)...
Jun 27 13:46:11 kali systemd[1]: Finished Anonymizing overlay network for TCP (multi-instance-master).
> sudo netstat -tanp | grep tor
tcp 0 0 127.0.0.1:9050 0.0.0.0:* LISTEN 43758/tor
tcp 0 0 192.168.85.139:36538 178.238.236.41:1337 ESTABLISHED 43758/tor
tcp 0 0 192.168.85.139:57824 162.55.131.67:9100 ESTABLISHED 43758/tor What do i am doing wrong?
| How to change Tor port in Kali |
For your reference:
*filter
-N RNNS
-A RNNS -p tcp ! --syn -j REJECT --reject-with tcp-reset
# accept (new) syn
-A RNNS -j ACCEPT-N ALLOW
# tcp (r)eset (n)ew but (n)ot (s)yn
# -j RNNS is fine too since the chain has a "fallback" verdict at the end
-A ALLOW -p tcp --dport 9001 -g RNNS
-A ALLOW -p tcp --dport 9030 -g RNNS
-A ALLOW -p tcp --dport 12345 -g RNNS
# for (new) udp, just accept
-A ALLOW -p udp --dport 54321 -j ACCEPT
# others' fate will be determined by the chain policy of INPUT
# because we came to this chain by -g
# but well, -g ALLOW was the last rule anyway, so -j would have worked too
# and you can -j DROP here anyway-P INPUT DROP
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -m conntrack --ctstate INVALID -j DROP
# -A INPUT -m conntrack --ctstate INVALID ! -p tcp -j DROP
# could only be of conntrack state NEW; oh well, also see UNTRACKED
-A INPUT -i lo -j ACCEPT
# -A INPUT -i lo -g RNNS
-A INPUT -p icmp --icmp-type echo-request -m limit --limit 2/second --limit-burst 5 -j ACCEPT
# chain policy; optimization / optional
-A INPUT -p icmp -j RETURN
# won't be ICMP
-A INPUT -g ALLOW-P FORWARD DROP
-P OUTPUT ACCEPT
COMMITNote that the order of the rules in the same chain could matter a lot, but certainly the order among rules that have no logical relation does not (see the chain ALLOW), although as an "optimization", we prioritize matching that are more "important" / likely to be true (see the first two --ctstate rules in the INPUT chain) when we can.
|
Could anyone help me with a review of my iptables rules (running a new Tor relay server), please?
I'm running a Debian GNU/Linux 11 (bullseye), fully updated.
I drop everything in INPUT chain by default, SSH port is censored, so if you see XXYYZ... I changed it to a custom port so that the bots have a little bit more work than just hit the 22.
I will copy-paste the rules.v4 file now:
# Latest revision on 2021-Jul-25*filter:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]--append INPUT --match conntrack --ctstate NEW --protocol tcp ! --syn --match comment --comment "protection: non-syn packets" --jump DROP
--append INPUT --match conntrack --ctstate INVALID --match comment --comment "protection: malformed packets" --jump DROP
--append INPUT --in-interface lo --match comment --comment "loopback: compulsory" --jump ACCEPT
--append INPUT --protocol icmp --icmp-type echo-request --match limit --limit 2/second --limit-burst 5 --match comment --comment "ICMP: ping only" --jump ACCEPT
--append INPUT --match conntrack --ctstate RELATED,ESTABLISHED --match comment --comment "Tor: traffic" --jump ACCEPT
--append INPUT --match conntrack --ctstate NEW,ESTABLISHED --protocol tcp --match tcp --destination-port XXYYZ --match comment --comment "SSH: global obfuscated" --jump ACCEPT
--append INPUT --protocol tcp --match tcp --destination-port 9001 --match comment --comment "Tor: OR" --jump ACCEPT
--append INPUT --protocol tcp --match tcp --destination-port 9030 --match comment --comment "Tor: Dir" --jump ACCEPTCOMMITThe current output of about one day's uptime is:
# iptables -L INPUT -v --line-numbersChain INPUT (policy DROP 29718 packets, 3008K bytes)
num pkts bytes target prot opt in out source destination
1 234 131K DROP tcp -- any any anywhere anywhere ctstate NEW tcp flags:!FIN,SYN,RST,ACK/SYN /* protection: non-syn packets */
2 374 45284 DROP all -- any any anywhere anywhere ctstate INVALID /* protection: malformed packets */
3 96 4800 ACCEPT all -- lo any anywhere anywhere /* loopback: compulsory */
4 24 902 ACCEPT icmp -- any any anywhere anywhere icmp echo-request limit: avg 2/sec burst 5 /* ICMP: ping only */
5 3736K 2726M ACCEPT all -- any any anywhere anywhere ctstate RELATED,ESTABLISHED /* Tor: traffic */
6 30 1800 ACCEPT tcp -- any any anywhere anywhere ctstate NEW,ESTABLISHED tcp dpt:XXYYZ /* SSH: global obfuscated */
7 12493 743K ACCEPT tcp -- any any anywhere anywhere tcp dpt:9001 /* Tor: OR */
8 7948 423K ACCEPT tcp -- any any anywhere anywhere tcp dpt:9030 /* Tor: Dir */The server seems to work like a charm, but I may be simply over-confident, for the lack of a better word.
| Review iptables on a VPS (running Tor non-exit relay) |
I'd do the following: uninstall the version offered by Debian, install the version offered by Mozilla itself, e.g. https://ftp.mozilla.org/pub/thunderbird/releases/60.2.1/ - just unpack a tar.gz to a directory of your choice.
It's advisable to use the latest stable release, e.g. 60.9.1 which should retain the same level of compatibility as 60.2.1 but even 60.9.1 has long been unsupported and contains known vulnerabilities. It's generally not advisable to run unsupported software especially web browsers and desktop mail clients.
|
I am thinking of trying the thunderbird add-on torbirdy
The problem is, it only works up to Thunderbird version 60.2.1 from October 2018. I am running Debian Buster which updates Thunderbird automatically and it's currently on 68.11.0
Is it worth somehow rolling back thunderbird to that version, and telling Debian to leave it alone? If so, how would that be done? Otherwise would it better to install the older version somehow alongside.
I wonder what can really be new in email, and what the constant updates to Thunderbird are actually updating. It has somehow become too incompatible with torbirdy for it to be fixed.
| peg thunderbird to older version or install a second instance |
I'm afraid vidalia appears to be retired: https://admin.fedoraproject.org/pkgdb/package/rpms/vidalia/ Probably, there isn't any repository available for F24 that contains it. If there is you have to find it first, there is no magic command for that part.
(By the way, the name was changed from Fedora Core to just Fedora a long time ago.)
|
I'm in the process of installing a (somewhat modified) Fedora Core 24 system, and am still trying to do things in the mostly right way.
How can I get dnf install vidalia (which, in quotes, has only Spanish results in google) to work?
I've seen RPM files for vidalia, but I'd prefer to add a new repo (like pkgs.org?) instead of grabbing the rpm file directly? I also want to get whatever version is presumably the "best" for Fedora Core 24.
I did dnf install tor, but rpm -ql tor (and dnf provides '*/vidalia') shows that tor doesn't include vidalia and neither does any repo I have currently installed.
I do know how to add new repos and have done this earlier:
sudo dnf install --allowerasing --best http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm`so I guess I'm looking for the magic command similar to the above that installs a repo that allows me to install vidalia properly.
| "dnf install vidalia" on Fedora Core 24? |
deb [arch=i386,amd64,armel,armhf] http://http.kali.org/kali kali-dev main contrib non-free
deb [arch=i386,amd64,armel,armhf] http://http.kali.org/kali kali-dev main/debian-installer
deb-src http://http.kali.org/kali kali-dev main contrib non-freedeb [arch=i386,amd64,armel,armhf] http://http.kali.org/kali kali main contrib non-free
deb [arch=i386,amd64,armel,armhf] http://http.kali.org/kali kali main/debian-installer
deb-src http://http.kali.org/kali kali main contrib non-freedeb [arch=i386,amd64,armel,armhf] http://security.kali.org/kali-security kali/updates main contrib non-free
deb-src http://security.kali.org/kali-security kali/updates main contrib non-freeOverwriting my /etc/apt/sources.list file with the lines above and then using apt-get update followed by apt-get upgrade solved the problem.
Initially my /etc/apt/sources.list file contained these two lines
deb http://http.kali.org/kali sana main non-free contrib
deb http://security.kali.org/kali-security/ sana/updates main contrib non-freeI got the solution from one of the answers in this forum
https://forums.kali.org/archive/index.php/t-142.html
|
I am trying to install TOR on Kali Linux 2016.2 but I am getting the following error message.
apt-get install tor
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libssl1.0.0 tor-geoipdb torsocks
Suggested packages:
mixmaster xul-ext-torbutton tor-arm polipo | privoxy apparmor-utils obfsproxy
The following NEW packages will be installed:
libssl1.0.0 tor tor-geoipdb torsocks
0 upgraded, 4 newly installed, 0 to remove and 11 not upgraded.
Need to get 3,034 kB of archives.
After this operation, 10.6 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Err:1 http://http.kali.org/kali sana/main amd64 libssl1.0.0 amd64 1.0.1k-3
404 Not Found
Err:2 http://http.kali.org/kali sana/main amd64 tor amd64 0.2.5.12-1
404 Not Found
Err:3 http://http.kali.org/kali sana/main amd64 torsocks amd64 2.0.0-3
404 Not Found
Err:4 http://http.kali.org/kali sana/main amd64 tor-geoipdb all 0.2.5.12-1
404 Not Found
E: Failed to fetch http://http.kali.org/kali/pool/main/o/openssl/libssl1.0.0_1.0.1k-3_amd64.deb 404 Not FoundE: Failed to fetch http://http.kali.org/kali/pool/main/t/tor/tor_0.2.5.12-1_amd64.deb 404 Not FoundE: Failed to fetch http://http.kali.org/kali/pool/main/t/torsocks/torsocks_2.0.0-3_amd64.deb 404 Not FoundE: Failed to fetch http://http.kali.org/kali/pool/main/t/tor/tor-geoipdb_0.2.5.12-1_all.deb 404 Not FoundE: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing? | Errors in installing Tor on Kali 2016.2 VM |
[The following links may not be the actual version you have, but are probably similar enough]. The torify command is a shell script,
which just calls torsocks which is another shell script that just does exec.
So you should just be able to provide multiple commands to torify like this:
torify sh -c 'curl ifconfig.me; myprogram -n myarg'The problem you have with torify /tmp/test-tor/download.sh is probably that the script you wrote should start with #!/bin/bash; some systems don't have a /usr/bin/bash. Make sure you chmod +x your script too.
|
Suppose command1 takes another command (say command2) as argument, with command2's arguments as the remaining arguments of comman1, i.e.
command1 command2 arg...When command2 is a made up of several commands (each of which might have its own arguments and options), e.g. when command2 is command 3; command 4 and command 3 | command 4, how do you specify command2 as an argument to command1?
Does my question belong to bash, command1, or both?The solution I can think of is: writing command2 as a bash script
and passing the script name in place of command2 as an argument to
command1.
But it seems not work in the following example:
$ torify /tmp/test-tor/download.sh
/usr/bin/torsocks: 162: exec: /tmp/test-tor/download.sh: not foundwhere the content of /tmp/test-tor/download.sh is:
#! /usr/bin/bashcurl ifconfig.me
myprogram -n myargI also would like to know if it is possible to solve the problem without writing a
script, because it seems overkill to write a script when command2
is short.
For example, when using tor with a program, I want to check my
external ip address by curl ifconfig.me, before running the
program
torify "curl ifconfig.me; myprogram -n myarg" but it doesn't work. | How to specify a compound command as an argument to another command? |
touching the file first confirms that you actually have the ability to create the file, rather than wasting time in an editor only to find out that the filesystem is read-only or some other problem.
|
Is there a benefit of creating a file with touch prior to edit.. like:
touch foo
vi fooversus getting it to editor straight-away? Like:
vi fooI see quite a few tutorials using the former (touch then vi).
| Use of touch and vi? |
You do not have the path that holds the file:
/opt/tsrm/compliance/cme/log/
That's where the error come from.
| I am getting the error:
touch: cannot touch `/opt/tsrm/compliance/cme/log/20121207.log`: No such file or directoryon the touch command: touch $LOGFILE
I also checked the link: touch: cannot touch `foo': No such file or directory, But I didn't understand the answer.
Note: I was also getting mkdir: cannot create directory; I fixed this by adding the -p option.
Could this be something with the version of Linux I am working in?
| touch: cannot touch file: No such file or directory [duplicate] |
You don't even need to use :; you can just > file (at least in bash; other shells may behave differently).
In practical terms, there is no real difference here (though the minuscule overhead of calling out to /bin/touch is a thing).
touch, however, can also be used to modify the timestamps on a file that already exists without changing or erasing the contents; further, > file will blow out any file that already exists. This can be worked around by instead using >> file.
One other difference with touch is that you can have it create (or update the timestamp on) multiple files at once (e.g. touch foo bar baz quux) with a more succinct syntax than with redirection, where each file needs its own redirection (e.g. >foo >bar >baz >quux).
Using touch:
$ touch foo; stat -x foo; sleep 2; touch foo; stat -x foo
File: "foo"
Size: 0 FileType: Regular File
Mode: (0644/-rw-r--r--) Uid: (991148597/redacted) Gid: (1640268302/redacted)
Device: 1,5 Inode: 8597208698 Links: 1
Access: Fri May 25 10:55:19 2018
Modify: Fri May 25 10:55:19 2018
Change: Fri May 25 10:55:19 2018
File: "foo"
Size: 0 FileType: Regular File
Mode: (0644/-rw-r--r--) Uid: (991148597/redacted) Gid: (1640268302/redacted)
Device: 1,5 Inode: 8597208698 Links: 1
Access: Fri May 25 10:55:21 2018
Modify: Fri May 25 10:55:21 2018
Change: Fri May 25 10:55:21 2018Using redirection:
$ > foo; stat -x foo; sleep 2; >> foo; stat -x foo
File: "foo"
Size: 0 FileType: Regular File
Mode: (0644/-rw-r--r--) Uid: (991148597/redacted) Gid: (1640268302/redacted)
Device: 1,5 Inode: 8597208698 Links: 1
Access: Fri May 25 10:55:21 2018
Modify: Fri May 25 10:56:25 2018
Change: Fri May 25 10:56:25 2018
File: "foo"
Size: 0 FileType: Regular File
Mode: (0644/-rw-r--r--) Uid: (991148597/redacted) Gid: (1640268302/redacted)
Device: 1,5 Inode: 8597208698 Links: 1
Access: Fri May 25 10:55:21 2018
Modify: Fri May 25 10:56:25 2018
Change: Fri May 25 10:56:25 2018 |
Never realized that you could do this until just now:
: >> fileIt seems to be functionally similar to:
touch fileIs there a reason why most resources seem to prefer touch over this shell builtin?
| When creating an empty file, why might one prefer 'touch file' over ': >> file'? |
Following sequence causes this error message:
$ mkdir foo
$ cd fooIn another terminal:
$ rm -r fooIn the previous terminal:
$ touch x
touch: cannot touch `x': No such file or directoryOf course, other events that also result in invalidating the current working directory (CWD) of a process that tries to create a file there also yield this error message.
|
What could cause touch to fail with this error message?
touch: cannot touch `foo': No such file or directoryNote that an error due to incorrect permissions looks different:
touch: cannot touch `foo': Permission denied | touch: cannot touch `foo': No such file or directory |
You can modify your umask to allow (for most implementations) more read/write privileges, but not executable, since generally the requested permissions are 0666.
If your umask is 022, you'll see touch make a 0644 file.
Interestingly, POSIX describes this behavior in terms of creat:If file does not exist:
The creat() function is called with the following arguments:The file operand is used as the path argument.
The value of the bitwise-inclusive OR of S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH is used as the mode argument.and it is only by following the links to creat, then to open, noticing the mention of umask and back-tracking to open (and creat) to verify that umask is supposed to affect touch.
For umask to affect only the touch command, use a subshell:
(umask 066; touch private-file)
(umask 0; touch world-writable-file)
touch file-as-per-current-umask(note that in any case, if the file existed beforehand, touch will not change its permissions, just update its timestamps).
|
It seems that whenever I create a file with touch the permissions are set to: -rw-r--r--.
Is there some way that I can configure the permissions with touch or does this have to be done after with a different command?
| How to set file permissions with touch command |
For GNU utilities, the full documentation is in the info page, where you can read:-f Ignored; for compatibility with BSD versions of `touch'.See historic BSD man pages for touch, where -f was to force the touch.
If you look at the source of those old BSDs, there was no utimes() system call, so touch would open the file in read+write mode, read one byte, seek back and write it again so as to update the last access and last modification time.
Obviously, you needed both read and write permissions (touch would avoid trying to do that if access(W_OK|R_OK) returned false). -f tried to work around that by temporarily changing the permissions temporarily to 0666!
0666 means read and write permission to everybody. It had to be that as otherwise (like with a more restrictive permission such as 0600 that still would have permitted the touch) that could mean during that short window, processes that would otherwise have read or write permission to the file couldn't any more, breaking functionality.
That means however that processes that would not otherwise have access to the file now have a short opportunity to open it, breaking security.
That's not a very sensible thing to do. Modern touch implementations don't do that. Since then, the utime() system call has been introduced, allowing changing modification and access time separately without having to mingle with the content of the files (which means it also works with non-regular files) and only needs write access for that.
GNU touch still doesn't fail if passed the -f option, but just ignores the flag. That way, scripts written for those old versions of BSD don't fail when ported to GNU systems. Not much relevant nowadays.
|
From man touch:
-f (ignored)But I don't get what is meant by ignored.
I've tried following:
$ ls -l file
-rw-rw-r-- 1 pandya pandya 0 Mar 20 16:17 file$ touch -f file
$ ls -l file
-rw-rw-r-- 1 pandya pandya 0 Mar 20 16:18 fileAnd noticed that it changes timestamps in spite of -f.
So, I want to know what -f stands for, or what it does.
| What is the use of the -f option for `touch`? |
You can use touch -r to use another file's timestamp instead of the current time (or touch --reference=FILE)
Here are two solutions. In each solution, the first command changes the modification time of the directory to that of the newest file immediately under it, and the second command looks at the whole directory tree recursively. Change to the directory (cd '.../(1997-05-20) The Colour and The Shape') before running any of the commands.
In zsh (remove the D to ignore dot files):
touch -r *(Dom[1]) .
touch -r **/*(Dom[1]) .On Linux (or more generally with GNU find):
touch -r "$(find -mindepth 1 -maxdepth 1 -printf '%T+=%p\n' |
sort |tail -n 1 | cut -d= -f2-)" .
touch -r "$(find -mindepth 1 -printf '%T+=%p\n' |
sort |tail -n 1 | cut -d= -f2-)" .However note that those ones assume no newline characters in file names.
|
I was wondering if anyone knows how to change the timestamps of folders recursively based on the latest timestamp found of the files in that folder.
So for example:jon@UbuntuPanther:/media/media/MP3s/Foo Fighters/(1997-05-20) The Colour and The Shape$ ls -alF
total 55220
drwxr-xr-x 2 jon jon 4096 2010-08-30 12:34 ./
drwxr-xr-x 11 jon jon 4096 2010-08-30 12:34 ../
-rw-r--r-- 1 jon jon 1694044 2010-04-18 00:51 Foo Fighters - Doll.mp3
-rw-r--r-- 1 jon jon 3151170 2010-04-18 00:51 Foo Fighters - Enough Space.mp3
-rw-r--r-- 1 jon jon 5004289 2010-04-18 00:52 Foo Fighters - Everlong.mp3
-rw-r--r-- 1 jon jon 5803125 2010-04-18 00:51 Foo Fighters - February Stars.mp3
-rw-r--r-- 1 jon jon 4994903 2010-04-18 00:51 Foo Fighters - Hey, Johnny Park!.mp3
-rw-r--r-- 1 jon jon 4649556 2010-04-18 00:52 Foo Fighters - Monkey Wrench.mp3
-rw-r--r-- 1 jon jon 5216923 2010-04-18 00:51 Foo Fighters - My Hero.mp3
-rw-r--r-- 1 jon jon 4294291 2010-04-18 00:52 Foo Fighters - My Poor Brain.mp3
-rw-r--r-- 1 jon jon 6778011 2010-04-18 00:52 Foo Fighters - New Way Home.mp3
-rw-r--r-- 1 jon jon 2956287 2010-04-18 00:51 Foo Fighters - See You.mp3
-rw-r--r-- 1 jon jon 2730072 2010-04-18 00:51 Foo Fighters - Up in Arms.mp3
-rw-r--r-- 1 jon jon 6086821 2010-04-18 00:51 Foo Fighters - Walking After You.mp3
-rw-r--r-- 1 jon jon 3033660 2010-04-18 00:52 Foo Fighters - Wind Up.mp3The folder "(1997-05-20) The Colour and The Shape" would have its timestamp set to 2010-04-18 00:52.
| How do I change folder timestamps recursively to the newest file? |
All the answers so far (as well as your example in the question) assume that you want to touch everything in the directory, even though you said "touch all folders". If it turns out the directory contains files and folders and you only want to update the folders, you can use find:
$ find . -maxdepth 1 -mindepth 1 -type d -exec touch {} +Or if your find implementation doesn't support the non-standard -mindepth/-maxdepth predicates:
$ find . ! -name . -prune -type d -exec touch {} +This:
$ touch -c -- */Should work in most shells except that:it will also touch symlinks to directories in addition to plain directories
it will omit hidden ones
if there's no directory or symlink to directory, it would create a file called * in shells other than csh, tcsh, zsh, fish or the Thompson shell (which would report an error instead). Here, we're using -c to work around it, though that could still touch a non-directory file called *.With zsh, to touch directories only, including hidden ones:
touch -- *(D/) |
I am trying to update the timestamps of all folders in the cwd using this:
for file in `ls`; do touch $file; doneBut it doesn't seem to work. Any ideas why?
| touch all folders in a directory |
At least in the GNU world:
touch --date=@1403970787 fileLike with date.
|
I know how to get a file's mtime in epoch format:
stat --format=%Y <file>But I have not been able to figure out how to set a file's mtime in epoch format. The touch(1) man page appears to only accept a "timestamp" value (more-or-less fixed format which uses months, days, hours, minues, etc) or a "mostly free format human readable date string".
Is there another utility I should be looking into?
Thanks.
| How do I set a file's mtime in epoch format? |
It doesn't stand for anything; it's not an abbreviation or initialism. It's a verb.
When you touch a file, you're "putting fresh fingerprints on it", updating its last-modified date (or creating it if it did not yet exist).
|
My question is not so much a question of computer science as it is a question of etymology.
The command touch changes file access and modification times.
What does 'touch' stand for?
| What does 'touch' stand for? |
You can't edit the contents of the public directory if you don't have write and execute access.You indicate you are attempting to create a new file. If the test file doesn't already exist in public, touch will attempt to create a new file. It cannot do this without the write and execute permissions over the parent directory. Execute is required to traverse the directory; write is required to add the inode entry for the new file. Apparently, you don't have one or both of these permissions.
If the test file does already exist in public, touch will, by default, update the modification time of the file. Only write access to the file is required for this, as the modification date/time is stored in the file's inode. If the file already exists, you will need to inspect the file's permissions using a command like ls -l public/test to determine if you have write access.The permissions bitmask on the directory, rwxrwxr-x, means:the root user, i.e. the owner of the directory, has write privileges to the directory as indicated by the first rwx block. This user can also read the directory (the r bit) and traverse it to access its contents (the x bit).
members of the root group, i.e. the group on the directory, who are not themselves the root user, also have similar privileges to read, write and traverse the directory as indicated by the second rwx blockAll other users only have read and execute rights, as indicated by the last r-x block. As noted, for directories, execute permissions allow you to traverse that directory and access its contents. See this question for more clarity on this.
How do I get permissions?
You will need to talk to your system administrator (which might be you!) to do one of the following:Make you the owner of the public/ directory using a command like chown user public/. This will be suitable if you are the only user who will need to have edit rights.
Create a new group with a suitable name, perhaps publiceditors, and set this as the group on the public/ directory using a command like chgrp publiceditors public/. Ensure you and any other users who require the ability to modify the directory are listed as members of the group. This approach works where multiple users need edit capability.
Make your user account a member of the root group (not something I would recommend).
Provide you with access to log in or masquerade as root, such as with sudo or su with the root password
Change the rights on the directory to grant all users write permissions, using a command like chmod o+w public. Be aware that this gives everyone on the box the ability to edit and delete files in the public directory.* You may not want this!*In the absence of other access control enforcement, such as mandatory access control in the kernel.
What do read, write and execute permissions mean in the context of a directory?
Assuming you're on a Linux box, on a directory, a read permission bit allows you to read the directory listing. The write permission bit allows you to update the directory listed, which is required for creating a file*, editing the name of a file, unlinking (deleting) a file. The execute bit allows you to traverse the directory, access its files etc. More information on Linux directory permissions.
* Actually, you're linking a file into the directory. Most times you will do this at the point of file creation, but there are more complex examples. For example, making a hard link to a file which originally existed elsewhere in the file system will require write access to the target directory of the link, despite the fact you're not creating a new file.Why write access to the directory?
You need to be able to write to the directory to add a reference to the relevant inode for the file you are adding.
|
I am trying to create a file in a directory but I am getting:
`touch`: cannot touch ‘test’: Permission deniedHere are my commands:
[user@xxx api]$ ls -l
total 184
...
drwxrwxr-x 2 root root 4096 2016-04-12 14:38 public
..
[user@xxx api]$ cd ./public
[user@xxx public]$ touch test
touch: cannot touch ‘test’: Permission denied | touch: cannot touch ‘test’: Permission denied |
You've misread what the presenter entered. This is what is actually given on the video:
mkdir -p lib/{login,signup,users,posts}
touch !!:2/{package.json,index.json}This extends the !! instruction to repeat the previous command, but the :2 modifier says use the second argument. So, here !!:2 is the lib/{login,signup,users,posts} component.
| Watching a video (https://vimeo.com/56166857 & https://www.youtube.com/watch?v=9CTfGS0gEOk @ 1m:34s), the presenter (TJ Holowaychuk) wrote:
touch !!:2{...}I can't find what !!:2 means anywhere.
I get the (repeat the previous command) !! but, the meaning of
!!:2I don't know, can't find an answer for and the search here returned no results for, so ... I'm stuck.
Context:
to create several directories at once, he wrote:
mkdir -p lib/{login,signup,users,posts}to create the same files in each of those directories, he wrote:
touch !!:2/{package.json,index.json}The output was:
touch lib/{login,signup,users,posts}/{package.json,index.json}The result was:
The two files were created in each of the directories.
| What does !!: mean in bash? [duplicate] |
The limitation is on the size of the arguments upon execution of a command. So the options are to execute a command with fewer arguments, for instance with xargs to run smaller batches, increase the limit (ulimit -s 100000 on Linux), not execute anything (do it all in the shell), or build the list in the tool that creates the files.
zsh, ksh93, bash:
printf '%s ' {1..1391803} | xargs touchprintf is builtin, so there's no exec, so the limit is not reached. xargs splits the list of args passed to touch to avoid breaking the limit. That's still not very efficient as the shell has to first create the whole list (slow especially with bash), store it in memory, and then print it.
seq 1391803 | xargs touch(assuming you have a seq command) would be more efficient.
for ((i=1; i<=1391803; i++)); do : >> "$i"; doneEverything is done in the shell, no big list stored in memory. Should be relatively efficient except maybe with bash.
POSIXly:
i=1; while [ "$i" -le 1391803 ]; do : >> "$i"; i=$(($i + 1)); doneecho 'for (i=1;i<=1391803;i++) i' | bc | xargs touchawk 'BEGIN {for (i=1; i<=1391803; i++) {printf "" >> i; close(i)}}' |
I have been testing find directory which is taking max inodes and while testing I had run
touch test_{1..1391803}.txtBut it's give me error "-bash: /usr/bin/touch: Argument list too long", now I'm running below command, but it's seems it will take Hugh time
ruby -e '1.upto(1391803) { |n| %x( touch "test_#{n}.txt" ) }'So the question is : is there any way to create multiple files in small amount of time ? should I touch 1 lac files per loop or any better way ?
Test Result :
No. 1
[root@dc1 inode_test]# time seq 343409 | xargs touchreal 0m7.760s
user 0m0.525s
sys 0m4.385sNo. 2
[root@test-server inode_test]# time echo 'for (i=1;i<=343409;i++) i' | bc | xargs touchreal 0m8.781s
user 0m0.722s
sys 0m4.997sNo. 3
[root@test-server inode_test]# time printf '%s ' {1..343409} | xargs touchreal 0m8.913s
user 0m1.144s
sys 0m4.541sNo. 4
[root@test-server inode_test]# time awk 'BEGIN {for (i=1; i<=343409; i++) {printf "" >> i; close(i)}}'real 0m12.185s
user 0m2.005s
sys 0m6.057sNo. 5
[root@test-server inode_test]# time ruby -e '1.upto(343409) { |n| File.open("#{n}", "w") {} }'real 0m12.650s
user 0m3.017s
sys 0m4.878s | Efficient way to create multiple files |
Use an explicit path to the file:
touch ./-
cat ./-GNU touch treats a file operand of - specially:A FILE argument string of - is handled specially and causes touch to
change the times of the file associated with standard output.For cat, the POSIX standard specifies that a file operand - should be interpreted as a request to read from standard input.
The double-dash convention is still in effect, but it's not for signalling the end of arguments but the end of options. In neither of these cases would - be taken as an option (a lone - can not be an option) but as an operand ("file name argument").Regarding your last question:
To protect the contents of a variable against being interpreted as a set of options when using it as
utility "$variable"use
utility -- "$variable"Note that if the utility is cat, sed, awk, paste, sort and possibly a few others (or GNU touch), and $variable is -, this will still cause the utility to do its special processing since, as said above, - is not an option. Instead, make provisions so that filenames, if they may start with or are equal to -, are preceded by a path, for example ./ for files in the current working directory.
A good habit is to use
for filename in ./*; dorather than
for filename in *; dofor example.
| How do I use GNU touch to update a file called -?
How do I use GNU cat to display a file called -?I'm running:
% cat --version | head -n1
cat (GNU coreutils) 8.29
% touch --version | head -n1
touch (GNU coreutils) 8.29Firstly, touch:
% touch -
% ls -l
total 0
% touch -- -
% ls -l -- -
ls: cannot access '-': No such file or directoryOk, I'll give up on creating a file with touch. Let's create it with date instead:
% date > -
% ls -l -
-rw-r--r-- 1 ravi ravi 29 Sep 8 19:54 -
%Now, let's try to cat it:
% cat -
% # I pressed ^D
% cat -- -
% # Same again - I pressed ^DI know I can work around with:
% > -and
% cat < -But why don't these GNU utils support the convention that -- means that everything following is treated as a non-option?
How do I use these tools in the general case, for example I have a variable with the contents -?
| How to `touch` and `cat` file named `-` [duplicate] |
The behaviour is expected, if rather non-obvious. At least on my system, touch does
utimensat(0, NULL, NULL, 0)in the first case (touch file), and
utimensat(0, NULL, [UTIME_OMIT, UTIME_NOW], 0)in the second (touch -m file). The first call is short-hand for "set the access and modification times to the current time"; the second says "leave the access time alone and change the modification time to the current time".
POSIX saysOnly a process with the effective user ID equal to the user ID of the file, or with write access to the file, or with appropriate privileges may use futimens() or utimensat() with a null pointer as the times argument or with both tv_nsec fields set to the special value UTIME_NOW. Only a process with the effective user ID equal to the user ID of the file or with appropriate privileges may use futimens() or utimensat() with a non-null times argument that does not have both tv_nsec fields set to UTIME_NOW and does not have both tv_nsec fields set to UTIME_OMIT.(times is the third argument to utimensat()). touch file falls under the first set of access restrictions: any write access to the file allows the access and modification times to be changed to "now". touch -m file falls under the second set of access restrictions: you need to be root or the owner of the file to be able to change the access and modification times to values which are not either both "now" or both "unchanged".
There are other ways of changing the access and/or modification times to "now" on files you don't own but can read or write:reading a file will update the access time only;
writing a file (without reading it) will update the modification time only. |
We have a file foobar not owned by me, but it is in my group:
$ ll
total 4,0K
-rw-rw-r-- 1 root hbogert 4 jan 19 12:27 foobarI can touch it and it will update all times:
$ stat foobar
File: 'foobar'
Size: 4 Blocks: 8 IO Block: 4096 regular file
Device: 801h/2049d Inode: 4869333 Links: 1
Access: (0664/-rw-rw-r--) Uid: ( 0/ root) Gid: ( 1000/ hbogert)
Access: 2017-01-19 12:27:04.499412133 +0100
Modify: 2017-01-19 12:27:04.499412133 +0100
Change: 2017-01-19 12:27:04.499412133 +0100
Birth: - $ touch foobar $ stat foobar
File: 'foobar'
Size: 4 Blocks: 8 IO Block: 4096 regular file
Device: 801h/2049d Inode: 4869333 Links: 1
Access: (0664/-rw-rw-r--) Uid: ( 0/ root) Gid: ( 1000/ hbogert)
Access: 2017-01-19 12:32:04.375412133 +0100
Modify: 2017-01-19 12:32:04.375412133 +0100
Change: 2017-01-19 12:32:04.375412133 +0100
Birth: -However, when I just want to change the modification time, it fails:
$ touch -m foobar
touch: setting times of 'foobar': Operation not permittedIs this expected behaviour?
| Why can touch change only all times, or nothing when not owner |
exiftool can set most of files metadata in addition to retrieving it, so it should just be a matter of:
TZ=UTC0 exiftool '-FileModifyDate<MediaModifyDate' ./*.movOr:
exiftool -api QuickTimeUTC '-FileModifyDate<MediaModifyDate' ./*.movOr recursively (also updating files in subdirectories):
exiftool -api QuickTimeUTC -r -ext mov '-FileModifyDate<MediaModifyDate' .By default, exiftool interprets those Media timestamps in QuickTime MOV files as local time even though the QuickTime specification says they're meant to be in UTC as that's what most cameras do. With TZ=UTC0, we tell it the local time is UTC (is 0 offset from UTC), with -api QuickTimeUTC, we tell it those times are meant to be interpreted as UTC as that seems to be the case for you. Both should achieve the same result.
Files without a MediaModifyDate would end up with a 1904-01-01 00:00:00 +0000 timestamp (-2082844800 epoch time) as that's the origin time for QuickTime timestamps.
To skip those, you can do:
TZ=UTC0 exiftool -d %s -if '$MediaModifyDate != -2082844800' \
-r -ext mov '-FileModifyDate<MediaModifyDate' .(using TZ=UTC0 instead of -api QuickTimeUTC as the latter doesn't seem to work when combined with -d %s specifically to format the time as Unix epoch time, which looks like a bug. Using other date formats would be timezone dependant so we couldn't compare to a fixed string like -2082844800)
If you wanted to use touch to set the mtime, you'd do:
mtime=$(
exiftool -api QuickTimeUTC -q -d %s -p '$MediaModifyDate' file.mov
) &&
[ "$mtime" != '0000:00:00 00:00:00' ] &&
touch -d "@$mtime" file.mov(using -api QuickTimeUTC does seem to work OK with -d %s when it's just about printing that number here. And yes, you do get 0000:00:00 00:00:00 and not -2082844800 when there's no MediaModifyDate. I guess that could change in the future).
|
In a shell, how to automatically set the modification (or creation) date and time of a Quicktime video file based on the metadata in the file with a single command (or a single command line)? For JPG files, we have exiv2 -T, but is there a similar command for .mov files?
To give an example, let's start with a file video.mov with the following metadata:
$ exiftool video.mov
ExifTool Version Number : 12.57
File Name : video.mov
Directory : .
File Size : 64 MB
File Modification Date/Time : 2023:07:04 02:53:05+02:00
File Access Date/Time : 2023:07:01 11:42:46+02:00
File Inode Change Date/Time : 2023:07:04 02:53:05+02:00
File Permissions : -rw-r--r--
File Type : MOV
File Type Extension : mov
MIME Type : video/quicktime
Major Brand : Apple QuickTime (.MOV/QT)
Minor Version : 0.0.0
Compatible Brands : qt
Media Data Size : 64215615
Media Data Offset : 36
Movie Header Version : 0
Create Date : 2023:07:01 11:42:00
Modify Date : 2023:07:01 11:42:46
Time Scale : 600
Duration : 0:00:45
Preferred Rate : 1
Preferred Volume : 100.00%
Preview Time : 0 s
Preview Duration : 0 s
Poster Time : 0 s
Selection Time : 0 s
Selection Duration : 0 s
Current Time : 0 s
Next Track ID : 6
Track Header Version : 0
Track Create Date : 2023:07:01 11:42:00
Track Modify Date : 2023:07:01 11:42:46
Track ID : 1
Track Duration : 0:00:45
Track Layer : 0
Track Volume : 0.00%
Image Width : 1920
Image Height : 1080
Clean Aperture Dimensions : 1920x1080
Production Aperture Dimensions : 1920x1080
Encoded Pixels Dimensions : 1920x1080
Graphics Mode : ditherCopy
Op Color : 32768 32768 32768
Compressor ID : hvc1
Source Image Width : 1920
Source Image Height : 1080
X Resolution : 72
Y Resolution : 72
Compressor Name : HEVC
Bit Depth : 24
Video Frame Rate : 29.997
Balance : 0
Audio Format : mp4a
Audio Channels : 2
Audio Bits Per Sample : 16
Audio Sample Rate : 44100
Purchase File Format : mp4a
Warning : [minor] The ExtractEmbedded option may find more tags in the media data
Matrix Structure : 1 0 0 0 1 0 0 0 1
Content Describes : Track 1
Media Header Version : 0
Media Create Date : 2023:07:01 11:42:00
Media Modify Date : 2023:07:01 11:42:46
Media Time Scale : 600
Media Duration : 0:00:45
Media Language Code : und
Gen Media Version : 0
Gen Flags : 0 0 0
Gen Graphics Mode : ditherCopy
Gen Op Color : 32768 32768 32768
Gen Balance : 0
Handler Class : Data Handler
Handler Vendor ID : Apple
Handler Description : Core Media Data Handler
Meta Format : mebx
Handler Type : Metadata Tags
Make : Apple
Model : iPhone SE (2nd generation)
Software : 16.5.1
Creation Date : 2023:07:01 13:42:00+02:00
Image Size : 1920x1080
Megapixels : 2.1
Avg Bitrate : 11.3 Mbps
Rotation : 90The best approach (to set the modification date) I could come up myself with so far is reading the output of
$ exiftool video.mov | grep "Media Modify Date" | cut -f 19-20 -d ' ', which is, in my example,
2023:07:01 11:42:46(which is correct as normalized to UTC or GMT because in real life, the video was taken at around 13:42:… CEST), replacing : in the date in output with -, and finally issuing
$ touch -d "2023-07-01 11:42:46 UTC" video.mov(my wild guess is that saying UTC is better than saying GMT above). This yields, as expected,
$ ls --full-time video.mov | cut -d ' ' -f 6-8
2023-07-01 13:42:46.000000000 +0200(the machine is in the time zone CEST, hence +0200). The result is what we want (because the time zone in which the video itself was taken was also CEST), but the process of getting there was manual.
How to process the date from the first command sequence (exiftool … -d ' ') automatically, so that we can issue both the first command and the second command (touch …) in a single command line or in a script?
Alternatively, the modification (or creation) time of the .mov video file has to be read from the metadata in the video file and set on the operating system level in some other way. How? (An aside: as the meta-data field Media Modify Date may be all-zeros for some files, e.g., for a file created by ffmpeg, we might need some more programming logic and try to switch to the values of some other fields in such a case, e.g., adding Date/Time Original and Media Duration if they are properly filled.)
Has anyone already done this task, perhaps, and we just need to run an already available program with appropriate parameters?
| How to automatically set the modification (or creation) time of a Quicktime video file based on its meta data? |
Like the last change time, the birth time isn’t externally controllable. On file systems which support it, the birth timestamp is set when a file is created, and never changes after that.
If you want to control it, you need to change the system’s notion of the current date and time, and create a new file.
|
Is it possible to change a file "Birth date" (according to the stat file "Birth" field)?
I can change the modification/access time with touch -t 200109110846 file, but can't find the corresponding option for "Birth".
| Change file "Birth date" for ext4 files? |
With zsh or bash or yash -o braceexpand:
$ mkdir dir-{01..50}
$ touch dir-{01..50}/file{01..50}.txt
$ ls dir-45
file01.txt file09.txt file17.txt file25.txt file33.txt file41.txt file49.txt
file02.txt file10.txt file18.txt file26.txt file34.txt file42.txt file50.txt
file03.txt file11.txt file19.txt file27.txt file35.txt file43.txt
file04.txt file12.txt file20.txt file28.txt file36.txt file44.txt
file05.txt file13.txt file21.txt file29.txt file37.txt file45.txt
file06.txt file14.txt file22.txt file30.txt file38.txt file46.txt
file07.txt file15.txt file23.txt file31.txt file39.txt file47.txt
file08.txt file16.txt file24.txt file32.txt file40.txt file48.txt$ tar -cf archive.tar dir-{01..50}With ksh93:
$ mkdir dir-{01..50%02d}
$ touch dir-{01..50%02d}/file{01..50%02d}.txt
$ tar -cf archive.tar dir-{01..50%02d}The ksh93 brace expansion takes a printf()-style format string that can be used to create the zero-filled numbers.With a POSIX sh:
i=0
while [ "$(( i += 1 ))" -le 50 ]; do
zi=$( printf '%02d' "$i" )
mkdir "dir-$zi" j=0
while [ "$(( j += 1 ))" -le 50 ]; do
zj=$( printf '%02d' "$j" )
touch "dir-$zi/file$zj.txt"
done
donetar -cf archive.tar dir-* # assuming only the folders we just created existsAn alternative for just creating your tar archive without creating so many files, in bash:
mkdir dir-01
touch dir-01/file{01..50}.txt
tar -cf archive.tar dir-01for i in {02..50}; do
mv "dir-$(( i - 1 ))" "dir-$i"
tar -uf archive.tar "dir-$i"
doneThis just creates one of the directories and adds it to the archive.
Since all files in all 50 directories are identical in name and contents, it then renames the directory and appends it to the archive in successive iterations to add the other 49 directories.
|
I am trying to create 50 directories (dir-01..dir-50). And I want to create 50 files (01.txt..50.txt) inside each of the 50 directories.
For example:
dir-01/01.txt..50.txt
dir-02/02.txt..50.txt
etc...I am able to create the the directories, but I am having trouble with creating the files inside each. I am also trying to compress all these afterwards into a tar file.
This is where I am at so far:
for i in {1..50};
do mkdir dir-$i;
done;
for j in {1..50};
do touch $j.txt.dir-*;
done;
tar -cf final.tar dir-{1..50}I know that second loop is wrong, but I am unsure how to proceed. Any advice is appreciated.
This seems to work, but I am unsure if it is correct in syntax or format:
for i in {1..50}; do
mkdir "dir-$i";
for j in {1..50}; do
touch "./dir-$i/$j.txt";
done;
done;tar -cf final.tar dir-{1..50} | Creating 50 directories with 50 files inside |
In bash (version 3.0 (2004) and above), ksh (since ksh93r (2006)) and zsh (version 5.0.6 (2014) and above):
touch {a..z}(note that only zsh supports characters other than ASCII letters and digits, none goes as far as perl's .. operator which inspired those shells operators).
With other zsh version (since 2.2 (1992)):
setopt braceccl
touch {a-z} | I need to create 26 files named a to z in single command. I thought touch command would be sufficient with the regex, but it doesn't expand [a-z] instead it creates a single file with name "[a-z]".
$ touch [a-z]Any way to achieve these?
Note:
$ bash -version
GNU bash, version 4.3.30(1)-release (i686-pc-linux-gnu) | How to create files named 'a to z' - any trick? [duplicate] |
GNU cp (from coreutils) can do this:
cp -r --attributes-only original_folder/* mirrored_folder/From man cp:--attributes-only
don't copy the file data, just the attributes
-R, -r, --recursive
copy directories recursivelyUsing find command as OP says xe is on MacOS and cp command has no --attributes-only option:
find original_folder/ -type d -exec \
sh -c 'mkdir -p mirrored_folder/${1#*/}' _ {} \; \
-o -type f -exec \
sh -c 'touch mirrored_folder/${1#*/}' _ {} \;Note that find solution creates fresh directories and files unlike the cp solution that was keeping their attributes (default: mode, ownership, timestamps).
|
I am trying to mirror the directory and file structure of a particular directory. However, I want the mirrored files to have no size. So for example, if I had the following directory tree:
original_folder
├── images
│ ├── image1.jpg (2 MB)
│ ├── image2.jpg (3 MB)
├── videos
│ ├── video1.mp4 (300 MB)
│ ├── video2.mp4 (400 MB)I want the following output:
mirrored_folder
├── images
│ ├── image1.jpg (0 b)
│ ├── image2.jpg (0 b)
├── videos
│ ├── video1.mp4 (0 b)
│ ├── video2.mp4 (0 b)I tried using the following command in original_folder:
cd original_folder
find . -name '*' -exec touch ../mirrored_folder/'{}' \;However, this command tries to execute touch ../mirrored_folder/./images/image1.jpg. Note the dot which messes the command up. How can I achieve what I'm trying to do?
| How to mirror directory structure and files with zero size? |
you can use the --attributes-only switch of cp for this purpose, eg.
find . -iname "*.txt" -exec cp --attributes-only -t dummy/ {} +From the man page of cp:
--attributes-onlydon't copy the file data, just the attributesThis will create empty files with all attributes of the original file preserved but no contents.
|
I want create empty files with the same name, but in another location.
Is it possible?find some files
use only filenames
touch an empty file in another placeSomething like this:
find . -type f -name '*.jpg' -exec basename {}.tmp | touch ../emptys/{} \; | Find and create empty files with the same name in another location |
Use find -exec for recursive touch, with command line args for dirs to process.
#!/bin/sh
for i in "$@"; do
find "$i" -type f -exec touch -r {} -d '+3 hour' {} \;
doneYou can run it like this:
./script.sh /path/to/dir1 /path/to/dir2 |
I have many big folders with thousands of files in them and I want to use touchto set their modification times to be "original time"+3 hours.
I got this script from a similar thread in superuser:
#!/bin/sh
for i in all/*; do
touch -r "$i" -d '+3 hour' "$i"
doneso I'm guessing what I need is to make it work in any directory instead of a fixed one (so I won't need to edit the script everytime I want to run it somewhere different) and for it to able to find and edit files recursively.
I have little experience using Linux and this is my first time setting up a bash script, though I do know a thing or two about programming (mainly in C).
thanks you all very much for the help :)
| Script for changing modification time of files and directories recursively |
-t doesn't accept epoch time, -d does
-d, --date=STRING
parse STRING and use it instead of current time -t STAMP
use [[CC]YY]MMDDhhmm[.ss] instead of current timeYou need to use -d or --date instead of -t and you need to put @ before epochtime format is used, as described in date manpages:
EXAMPLES
Convert seconds since the epoch (1970-01-01 UTC) to a date $ date --date='@2147483647'Example:
touch --date=@1442968132 test.txtIf you want to change modify time only, use -m or --time modify or --time mtime, without it both modify and access times are changed.
-m change only the modification time --time=WORD
change the specified time: WORD is access, atime, or use: equivalent to -a WORD is modify or mtime: equivalent to -mExamples:
$ touch --date=@1442968132 test
$ stat test
File: test
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: fd03h/64771d Inode: 43266017 Links: 1
Access: (0664/-rw-rw-r--) Uid: ( 1000/ user1) Gid: ( 1000/ user1)
Context: unconfined_u:object_r:user_home_t:s0
Access: 2015-09-23 02:28:52.000000000 +0200
Modify: 2015-09-23 02:28:52.000000000 +0200
Change: 2018-11-23 11:34:59.893888360 +0100
Birth: -$ touch --date=@1542968132 test
$ stat test
File: test
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: fd03h/64771d Inode: 43266017 Links: 1
Access: (0664/-rw-rw-r--) Uid: ( 1000/ user1) Gid: ( 1000/ user1)
Context: unconfined_u:object_r:user_home_t:s0
Access: 2018-11-23 11:15:32.000000000 +0100
Modify: 2018-11-23 11:15:32.000000000 +0100
Change: 2018-11-23 11:35:06.893888073 +0100
Birth: -$ touch -m --date=@1342968132 test
$ stat test
File: test
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: fd03h/64771d Inode: 43266017 Links: 1
Access: (0664/-rw-rw-r--) Uid: ( 1000/ user1) Gid: ( 1000/ user1)
Context: unconfined_u:object_r:user_home_t:s0
Access: 2018-11-23 11:15:32.000000000 +0100
Modify: 2012-07-22 16:42:12.000000000 +0200
Change: 2018-11-23 11:35:22.300887441 +0100 |
Edit: Better worded question: How do I only use the touch command to set the modification time of a file to the unix epoch?
I know that the unix epoch value can be retrieved using "data %s", but how do I use the touch command (and only that command) to set the modification time to the unix epoch?
Edit2:
So, I found that this runs without any errors:
touch -m -d ”@$(date +%s)” fileexample.txtIs this a correct way of setting the modification time of a file to the Unix epoch?Original Question (disregard)...:
Using the Linux manual for the “touch” command, show the command that you would
use to set the modification time of a file to the Unix epoch.I understand that the Unix epoch is the amount of second (or miliseconds, I forgot) that has passed since the epoch (1970, January, 01)
What does the question mean by saying: setting the time "to the Unix epoch"?
So, Is it basically asking for today's time, or 1970 01 01, or...?
I know the command for this would be:
touch -m -t time fileBut what time do I set it to?
Also, am I meant to use the unix epoch format for the time in the command?
| Use touch command to set modification time of a file to the Unix epoch |
You need to use - foo format:
$ ls -l file
-rw-r--r-- 1 terdon terdon 0 Nov 29 11:05 file
$ touch -d '-1 week' file
$ ls -l file
-rw-r--r-- 1 terdon terdon 0 Nov 22 11:06 file |
I want to change the created timestamp of many images one week ago.
Code
% http://askubuntu.com/a/62496/25388
touch -d "7 days ago" *.pngOutput
touch: invalid date format ‘1 one ago’OS: Debian 8.5
| How to change created time stamp one week ago? |
Updated Answer
I stumbled across this gem
touch -r filename -d '+8 days' filenameFrom the info coreutils touch invocation (Thank you @don_crissti ):'-r FILE'
'--reference=FILE'
Use the times of the reference FILE instead of the current time.
If this option is combined with the '--date=TIME' ('-d TIME')
option, the reference FILE's time is the origin for any relative
TIMEs given, but is otherwise ignored. For example, '-r foo -d
'-5 seconds'' specifies a time stamp equal to five seconds before
the corresponding time stamp for 'foo'. If FILE is a symbolic
link, the reference timestamp is taken from the target of the
symlink, unless '-h' was also in effect.If you want variable expansion you can use soft quotes around the -d argument like so.
DAYS=8
touch -r filename -d "+${DAYS} days" filenameSample:
$ ls -l foo.bar
-rw-r--r-- 1 usr usr 69414810 Nov 10 2016 foo.bar
$ TEST=100
$ touch -r foo.bar -d "+${TEST} days" foo.bar
$ ls -l foo.bar
-rw-r--r-- 1 usr usr 69414810 Feb 24 2017 foo.bar |
This sounds like an easily researched question. It isn't. I'm following the following highly recommended post on an Ubuntu Stack Exchange site that I happened to run across. But the suggestion doesn't work on Red Hat Enterprise Linux ES release 4. I would have expected it to, but it fails, as detailed below.
This is the suggestion: Specifically, the poster recommends If you want to modify the file relative to its existing modification
time instead, the following should do the trick:
touch -d "$(date -R -r filename) - 2 hours" filenameThis does not work for me under Redhat. The minus sign is ignored and the time is set ahead two days just as if I'd entered
touch -d "$(date -R -r filename) + 2 hours" filenameFor example:
$ ls -al test
-rw-r----- 1 sc1478 dev 5 Oct 27 12:59 test$ touch -d "$(date -R -r test) - 8 days" test$ ls -al test
-rw-r----- 1 sc1478 dev 5 Nov 4 2016 test$ touch -d "$(date -R -r test) + 8 days" test$ ls -al test
-rw-r----- 1 sc1478 dev 5 Nov 12 2016 testWhether I use a minus sign or a plus sign, the date is adjusted forward.
Is this a bug in some version of touch?
Is there another way to adjust a file's timestamp relative to its current timestamp?
| How to use touch to set modified/created timestamp of a file? |
You can investigate what might be happening by running sshfs with option -o debug. It prints a lot of information on the basic filesystem operations done by a touch test command. An example operation is:
unique: 209, opcode: LOOKUP (1), nodeid: 1, insize: 45, pid: 10641
LOOKUP /test
getattr /test
NODEID: 44
unique: 209, success, outsize: 144The relevant part is that a getattr call was done, and it ended in success.
When you do a successful touch on a non-existant file the operations we see are (removing the details):
getattr /test
unique: 190, error: -2 (No such file or directory), outsize: 16
create flags: 0x8841 /test 0100644 umask=0022
fgetattr[140469187119648] /test
flush[140469187119648]
utime /test 1507647885 1507647885
getattr /test
flush[140469187119648]
release[140469187119648] flags: 0x8801We see the getattr test for the file fails, which is normal as it does not exist, so we go on to create the file.
If the file is now removed on the server, and we do the touch again on the client we see a different sequence:
getattr /test
unique: 215, success, outsize: 144
open flags: 0x8801 /test
unique: 216, error: -2 (No such file or directory), outsize: 16Now the getattr says the file still exists, so touch goes on to open() the file, but this results in your error message: the file does not really exist at all.
So it all seems to be a problem of the client cache of what files exist being too slow to catch up with changes at the remote. The simplest answer is to mount your remote with a shorter timeout for the getattr call, i.e. the stat() system call. This should work for you
sshfs -o cache_stat_timeout=0 ... |
Machine A's file system is mounted on machine B via sshfs. A process running on B, which was initiated from A by ssh touches a file on the mounted file system of A to communicate a signal; the signal (file) is then removed by A. This works reliably the first time the file is created/destroyed (touch/rm).
However, if a second process (again, running on B, spawned from A) tries to touch exactly the same file, the following error is sporadically thrown:
`touch: cannot touch '/path/to/file': No such file or directory`.The path is valid as judged by the fact that attempts to touch it manually after the error is thrown are uniformly successful. As mentioned, the error is sporadic (complicating attempts to debug), but only occurs when the file is touched after already having undergone a cycle of creation/deletion.
The actions that intermittently produce an error (touch, rm, touch) are separated in time so concurrent access is unlikely to be the culprit (i.e., the second touch does not happen until the file produced by the first touch is removed). Thinking the cause might stem from file system buffering, sync is called from A after removing the file, to no avail. Calling sync from B immediately before touching the file also does not help, though I do not know whether B's sync call affects the file system of A (the version of sync on B lacks the -f option for explicit file system specification; I tried to call sync on A from the process running on B via ssh user@A sync before touching but the process seems to exit without error just after the sync-over-ssh call since the remaining lines including the touch statement are not executed; perhaps because it is not possible to ssh from the server back to the client on a process initiated by ssh from the client to the server).
How may the cause of this file system-related error be determined?
| re-touching files over sshfs |
With zsh:
dirs=(*(/))
mkdir -- $^dirs/doc
touch -- $^dirs/doc/doc1.txt(/) is a globbing qualifier, / means to select only directories.
$^array (reminiscent of rc's ^ operator) is to turn on a brace-like type of expansion on the array, so $^array/doc is like {elt1,elt2,elt3}/doc (where elt1, elt2, elt3 are the elements of the array).
One could also do:
mkdir -- *(/e:REPLY+=/doc:)
touch -- */doc(/e:REPLY+=/doc1.txt:)Where e is another globbing qualifier that executes some given code on the file to select.
With rc/es/akanga:
dirs = */
mkdir -- $dirs^doc
touch -- $dirs^doc/doc1.txtThat's using the ^ operator which is like an enhanced concatenation operator.
rc doesn't support globbing qualifiers (which is a zsh-only feature). */ expands to all the directories and symlinks to directories, with / appended.
With tcsh:
set dirs = */
mkdir -- $dirs:gs:/:/doc::q
touch -- $dirs:gs:/:/doc/doc1.txt::qThe :x are history modifiers that can also be applied to variable expansions. :gs is for global substitute. :q quotes the words to avoid problems with some characters.
With zsh or bash:
dirs=(*/)
mkdir -- "${dirs[@]/%/doc}"
touch -- "${dirs[@]/%/doc/doc1.txt}"${var/pattern/replace} is the substitute operator in Korn-like shells. With ${array[@]/pattern/replace}, it's applied to each element of the array. % there means at the end.
Various considerations:
dirs=(*/) includes directories and symlinks to directories (and there's no way to exclude symlinks other than using [ -L "$file" ] in a loop), while dir=(*(/)) (zsh extension) only includes directories (dir=(*(-/)) to include symlinks to directories without adding the trailing slash).
They exclude hidden dirs. Each shell has specific option to include hidden files).
If the current directory is writable by others, you potentially have security problems. As one could create a symlink there to cause you to create dirs or files where you would not want to. Even with solutions that don't consider symlinks, there's still a race condition as one may be able to replace a directory with a symlink in between the dirs=(*/) and the mkdir....
|
Suppose I have a directory /, and it contains many directories /mydir, /hisdir, /herdir, and each of those need to have a similar structure.
For each directory in /, there needs to be a directory doc and within it a file doc1.txt.
One might naively assume they could execute
mkdir */doc
touch */doc/doc1.txtbut they would be wrong, because wildcards don't work like that.
Is there a way to do this without just making the structure once in an example then cping it to the others?
And, if not, is there a way to do the above workaround without overwriting any existing files (suppose mydir already contains the structure with some data I want to keep)?
EDIT: I'd also like to avoid using a script if possible.
| Make many subdirectories at once |
You need
touch "${toto}hihi.log"The problem is that the shell cannot know without the braces how many characters are part of the variable name. Thus it treats all legal characters as a part of the name. In this case that is everything before the .; i.e. the shell uses the non-existing variable $totohihi.
In general it helps to use the shell option -x to see what is going on:
set -x
touch "$totohihi.log"
+ touch .log |
I have this variable :
toto=123456
why does touch "$toto.hihi.log" works and creates a file called 123456.hihi.log
but touch "$totohihi.log" doesn’t do anything ?
| creating a file with touch using a variable |
The touch command itself cannot read from stdin, but you can do it with the help of xargs:
grep "hello(.*)" file.txt | xargs -I file_name touch file_nameEdit:
It the input for xargs contains a line ending with a backslash (\), a file with a newline in its name would be created. The question does not specify what would be the ecpected result in this case.
Example: The input
foo\
barwould result in a single file named foo\nbar. Adding option -d '\n' to the xargs command would change the behavior to creating two files foo\ and bar.
|
I want to be able to use the touch command with the pipeline to create multiple files depending on the output of a command.
Like for example:
grep "hello(.*)" file.txt | touchBut it doesn't work!
How can I achieve this?
| Usage of touch with pipeline |
Simply add a minus sign:
TZ=ZZZ0 touch -t "$(TZ=ZZZ-0:30 date +%Y%m%d%H%M.%S)" $HOME/referenceOr invert your timezone trick:
TZ=ZZZ0:30 touch -t "$(TZ=ZZZ0 date +%Y%m%d%H%M.%S)" $HOME/referenceIf you need to go beyond the range of timezone offsets, standard shell utilities notoriously lack a way to manipulate date. Various people have done the job of implementing date calculations in Bourne shell, so one option is to download one of these (a few are listed in Date arithmetic in Unix shell scripts). Another option is to install GNU coreutils, specifically its date command which lets you typeset dates such as now + 30 minutes. You can also install a more sophisticated scripting environment such as Perl and use its date manipulation libraries.
|
I have created the file which is 30 minutes old by using following command
TZ=ZZZ0 touch -t "$(TZ=ZZZ0:30 date +%Y%m%d%H%M.%S)" $HOME/referenceSimilarly how can I create a file 30 minutes of future time.
Ex: at 5:00 PM I want to touch the file to be at 5:30 PM
| Touch the file to future time stamp |
The last part of your script, writing to each file, will result in the files’ last modification times all being updated to the current time. Changing times using touch should be the last thing you do to your files.
Note that touch can’t change the creation time (on file systems that track it); see How to change files creation time? (touch changes only modified time) for details.
|
I would like to automate the creation of some files so I created a script.
I want also to specify the creation date of those files.
In a terminal for example, to create a file.txt with creation date of 12 of May 2012 I could touch as seen bellow,
touch -d 20120512 file.txtListing that file confirms the date,
-rw-rw-r-- 1 lenovo lenovo 0 May 12 2012 file.txtIf I apply the above in a script the files that I am creating all have the current time as creation time and not what I've specified.
What am I doing wrong here?
Script
#!/bin/bash##################################
#Generate dat and snapshot files.#
##################################
srv_dir="/home/lenovo/Source/bash/srv"
main_dir="${srv_dir}/main"
database_dir="${main_dir}/Database"
dat_file="${main_dir}/remote.dat"if [[ -e ${main_dir} ]]; then
echo "${main_dir} allready exists."
echo "Aborting..."
exit 0
fi# Create directories.
mkdir -p ${database_dir}# Create files.
if [[ $1 == "--dat-newer" ]]; then
# User wants dat file to be the latest modified file.
# Create dat file with date as 'now'.
touch ${dat_file} # Create snapshots with older dates.
touch -d 20210511 "${database_dir}/snapshot001"
touch -d 20210510 "${database_dir}/snapshot002"
touch -d 20210512 "${database_dir}/snapshot004"
touch -d 20210514 "${database_dir}/snapshot003"
else
# Create an old dat file.
touch -d 20210512 "${dat_file}" # Create snapshots with older dates.
touch -d 20210511 "${database_dir}/snapshot001"
touch -d 20210510 "${database_dir}/snapshot002"
touch -d 20210512 "${database_dir}/snapshot004" # Create snapshot003 with date as 'now'.
touch "${database_dir}/snapshot003"
fi# populate dat and snapshot files with data.
echo "Data of ${dat_file}" > "${database_dir}/snapshot001"
echo "Data of snapshot001" > "${database_dir}/snapshot001"
echo "Data of snapshot002" > "${database_dir}/snapshot002"
echo "Data of snapshot003" > "${database_dir}/snapshot003"
echo "Data of snapshot004" > "${database_dir}/snapshot004" | Can't specify file creation date |
The simplest way I could find is:
touch $(paste -d '.' <(printf "%s\n" File{001..005}) \
<(printf "%s\n" {000..004}))This will create
File001.000 File002.001 File003.002 File004.003 File005.004To understand how this works, have a look at what each command prints:
$ printf "%s\n" File{001..005}
File001
File002
File003
File004
File005$ printf "%s\n" {000..004}
000
001
002
003
004$ paste -d '.' <(printf "%s\n" File{001..005}) \
> <(printf "%s\n" {000..004})
File001.000
File002.001
File003.002
File004.003
File005.004So, all together, they expand to
touch File001.000 File002.001 File003.002 File004.003 File005.004 Creating 5 files with random names is much easier:
$ for i in {1..5}; do mktemp File$i.XXX; done
File1.4Jt
File2.dEo
File3.nhR
File4.nAC
File5.Fd8To create 5 files with random 5 alphabetical character names and random extensions, you can use this:
$ for i in {1..5}; do
mktemp $(head -c 100 /dev/urandom | tr -dc 'a-z' | fold -w 5 | head -n 1).XXX
done
jhuxe.77b
cwvre.0BZ
rpxpp.ug1
htzkq.f9W
bpgor.BakFinally, to create 5 files with random names and no extensions, use
$ for i in {1..5}; do mktemp -p ./ XXXXX; done
./90tp0
./Hhn4U
./dlgr9
./iVcn4
./WsJIx |
I'm trying to create some files that has different names and with different extensions. Let say I want to create for example 3 files with following name and extension:
File001.000
File002.001
File003.002Or with alphabetical extension:
File001.A
File002.B
File003.CAlso it would be better if I could create files with random names and extension.
Filexct.cbb
Filedht.ryt
Filefht.vbf | How to create multiple files/directories with randomized names? |
You can do that with find:
find . -mindepth 1 -type d -exec touch "{}/README" \;Explanation-mindepth 1 will set the minimum depth, to avoid including the current directory
-type d will only find directories
-exec will run a command
{} contains the path of the found directoryIf you want to use only builtin shell commands:
for dir in *; do if [ -d "$dir" ]; then touch "$dir/README"; fi; doneExplanationfor will loop over every element in *, meaning all files in the current directory. dir will contain the current element during the loop.
if [ -d $dir ] checks if the element is a directory and only then
creates a file called README in the directory name contained in $dir |
For the following tree structure:
.
└── dir1
└── dir2
└── dir3What would be a simple way to create a file (could be empty), for every directory, so the resulting tree will look like:
.
├── dir1
│ ├── dir2
│ │ ├── dir3
│ │ │ └── README
│ │ └── README
│ └── README
└── README | How to create a file for every directory on a tree? |
The problem is that globs (the */ is a glob) are expanded by the shell before launching the command. And brace expansions happen before globs. What this means is that */{credits,links,notes} becomes '*/credits' '*/links' '*/notes' and then these globs are expanded by the shell, and because the files haven't been created yet, the globs are expanded to themselves.
You can see the same behavior with any glob that doesn't match anything. For example:
$ echo a*j
a*jWhile when it does match:
$ touch abj
$ echo a*j
abjComing back to your case, because the files don't actually exist, the command you are running becomes:
touch '*/credits' '*/links' '*/notes'If you create one of them, you can see that things change:
$ touch Psy/credits
$ touch */{credits,links,notes}
touch: cannot touch '*/links': No such file or directory
touch: cannot touch '*/notes': No such file or directorySince we now have one file that does match the */credits glob, the file Psy/credits, that one works but the other two give errors.
The right way to do what you are attempting is something like this:
for d in */; do touch "$d"/{credits,links,notes}; doneWhich results in:
$ tree
.
├── abj
├── Eng
│ ├── credits
│ ├── links
│ └── notes
├── IT
│ ├── credits
│ ├── links
│ └── notes
├── IT_workshop
│ ├── credits
│ ├── links
│ └── notes
├── LA
│ ├── credits
│ ├── links
│ └── notes
├── OS
│ ├── credits
│ ├── links
│ └── notes
├── OS_lab
│ ├── credits
│ ├── links
│ └── notes
├── Psy
│ ├── credits
│ ├── links
│ └── notes
├── Python
│ ├── credits
│ ├── links
│ └── notes
└── Python_lab
├── credits
├── links
└── notes | This is the output of tree:
[xyz@localhost Semester1]$ tree
.
├── Eng
├── IT
├── IT_workshop
├── LA
├── OS
├── OS_lab
├── Psy
├── Python
└── Python_lab9 directories, 0 filesI want to create 3 common files (named credits, links and notes) in each of these directories using touch.
I tried this command:
[xyz@localhost Semester1]$ touch */{credits,links,notes}and this was the output:
touch: cannot touch ‘*/credits’: No such file or directory
touch: cannot touch ‘*/links’: No such file or directory
touch: cannot touch ‘*/notes’: No such file or directoryWhy did the command not work as I expected it to?
BTW, I'm using CentOS Linux 7.
| Why am I not able to use * with touch in path? [duplicate] |
I was very thankful for all the valuable time you guys spent answering my question and combining both the answers I found the best solution.
IF you have messed up with the coreutils then the best thing to do is download the coreutils file from the repository.
As we all know that .deb files are basically archive, open it with the file-roller and extract the package and replace the necessary files, set the required permissions and reboot.
Its done.
|
After updating GNOME to 3.20.2 I had some problems with my touchpad so in that confusion I mistakenly deleted /usr/bin/touch and after that I even became more stupid and deleted /bin/touch.
Now after this I can't seem to install any of the programs.
Here's the error generated in installing a program..
user1@pqrx:~$ sudo apt-get install gir1.2-gtop-2.0
[sudo] password for user1: Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
gir1.2-gtop-2.0
0 upgraded, 1 newly installed, 0 to remove and 1 not upgraded.
Need to get 0 B/54.6 kB of archives.
After this operation, 104 kB of additional disk space will be used.
Selecting previously unselected package gir1.2-gtop-2.0:amd64.
(Reading database ... 351267 files and directories currently installed.)
Preparing to unpack .../gir1.2-gtop-2.0_2.34.0-1_amd64.deb ...
Unpacking gir1.2-gtop-2.0:amd64 (2.34.0-1) ...
Setting up gir1.2-gtop-2.0:amd64 (2.34.0-1) ...
sh: 1: touch: not found
update-kali-menu: error: Can't open /var/lock/kali-menu: No such file or directory
E: Problem executing scripts DPkg::Post-Invoke '[ ! -x /usr/share/kali-menu/update-kali-menu ] || /usr/share/kali-menu/update-kali-menu wait_dpkg'
E: Sub-process returned an error codeAny help will be much appreciated.
| Deleted /usr/bin/touch and /bin/touch. Can't seem to install anything now, nor create any files? |
In terms of tools used: no.
touch will fail (rightly) if you are trying to operate in a directory that does not exist, and mkdir does precisely one thing: create directories, not normal files.
Two different jobs mandate two different tools.
That said, if you're talking about efficiency in terms of the number of lines in a script, or the readability of one, you could put it into a function:
seedfile() {
mkdir -p -- "$(dirname -- "$1")" &&
touch -- "$1"
}seedfile /path/to/location/one/file.txt
seedfile /path/to/somewhere/else/file.txt
seedfile local/paths/work/too/file.txt |
For now i use this:
mkdir -p a/b/c/d/e;
touch a/b/c/d/e/file.abc; Is there more efficient ways?
| Create file in subdirectories that doesn't exist (../new_folder/new_folder/new_file.ext) |
Simply like that :
$ touch ../lastname/test2.txtNote that instead of touch, you can use >¹
$ > ../lastname/test2.txtYou can also use an absolute path
$ > /Users/Directories/lastname/test2.txtBeware that it would truncate files if they existed beforehand while touch would only update their access and last modification time.¹ not in (t)csh nor fish though where you'd get an error, nor in zsh where it would run the $NULLCMD, redirecting an actual command that produces no output such as true or printf would work in any shell.
|
Suppose my current working directory is:
/Users/DirectoriesUnder Directories, there are two separate directories called: firstname & last name. I move into the first name directory:
$ cd firstnameand inside firstname, I want to create an empty file called test1.txt, so I type:
$ touch test1.txtThis is where I am stuck: without leaving firstname, I want to create a file called test2.txt in the directory lastname. I've tried this, but it doesn't seem to work. Thanks in advance.
$ touch test2.txt../lastname | Without changing your current directory, create an empty file in another directory in Linux? |
According to this hp man page for touch: http://h20565.www2.hp.com/hpsc/doc/public/display?docId=emr_na-c02273390
... the command expects the following form for touch:
touch time_str file_name
That form is recognized when neither the -r option, the -t
option, nor the -- option delimiter is specified, and the first operand consists of all decimal digits.
|
On Linux:
$ touch 1 12No problem,create 1 and 12.
On SysV or HP-UX 11.31:
$ touch 1 12
date: bad conversionI have tried with LANG=C, same error.
Why?
| date: bad conversion error on HP-UX but not on Linux |
You can prevent hackers from using PHP code to change modification time (mtime) of files that are writeable by your web server by disabling those PHP functions (such as touch) using [disable_functions][1] option in php.ini configuration file.
However, tracking modification time is not the right approach because the modification time of files do not change when they are uploaded to your server (i.e. this time could be much earlier than the time when your system is breached). A better approach is to track status changed time (ctime) of the inode file. To demonstrate what I mean:
$ touch test.txt
$ stat test.txt
File: ‘test.txt’
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
...
Access: 2014-10-28 05:51:10.329081380 +0000
Modify: 2014-10-28 05:51:10.329081380 +0000
Change: 2014-10-28 05:51:10.329081380 +0000$ touch -t 10011234 test.txt
$ stat test.txt
File: ‘test.txt’
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
...
Access: 2014-10-01 12:34:00.000000000 +0000
Modify: 2014-10-01 12:34:00.000000000 +0000
Change: 2014-10-28 05:52:57.669657564 +0000 <= unadulterated by touchWithout root access, I think it is quite impossible to modify ctime.
|
I don't want anybody to create a file then change the creation date to backward date(For example using touch or system call).
In my Ubuntu hosting account I'm getting many hacked php code getting uploaded.
Disallowing them to change the time of file when it landed will help me locate new files easily.
What is the way to achieve it? I could not find answer anywhere!
| How to disallow file modification time change for non root users |
Simply write nothing to the file:
:> "$filenameTarget"This will empty the file if it already exists, and create it (empty) if it doesn't. You need to have the appropriate permissions (the file must be writeable if it already exists, the containing directory must be writeable if the file doesn't already exist).
| I want to empty current file so I do: touch it, remove it and touch because I do not want to remove non-existing file; example
touch "$filenameTarget"
rm "$filenameTarget"
touch "$filenameTarget"I want to be very careful with deletes.
What is the correct philosophy here?
OS: Debian 8.5
| How to touch, rm and touch in Unix? [duplicate] |
From man ls:
In addition, for each directory whose contents are displayed, the total number of
512-byte blocks used by the files in the directory is displayed on a line by
itself, immediately before the information for the files in the directory.The minimum number of blocks allocated to a file depends on OS, file system type etc, so there is no direct way to influence the number shown.
| the question is, how can control the ls -l total output ?
first impression with example that give us total = 0
els3@els3PC:~/test$ touch file
els3@els3PC:~/test$ ls -l
total 0
-rw-r--r-- 1 els3 els3 0 Jul 20 12:05 fileAs i mention this example give us this result total = 0 by creating empty file.
in other way I will try to create a non empty file2 contain '3ls3' .
els3@els3PC:~/test$ cat > file2
3ls3
^C
els3@els3PC:~/test$ cat file2
3ls3
els3@els3PC:~/test$ ls -l
total 4
-rw-r--r-- 1 els3 els3 5 Jul 20 12:11 file2this second example give us total 4 by creating a non empty file.
the hole Q is how can i get for e.g total 1 or total 2 etc.. by creating a new file.
| How Can i control the 'total' output in 'ls -l' command? [duplicate] |
You could use a combination of date and touch, here GNU coreutils.
If I read you correctly you want a specific date and keep file time, as in HMS. Not set each file say 300 days prior to the current value.
You can create that time by combining the string 2014-05-25 with the extracted time from the files by using date, for example:
$ date +"2014-05-25 %T.%N" -r file.jpg
2014-05-25 18:06:28.277679656Then combine by doing something like:
for f in *.jpg; do touch -d "$(date +"2014-05-25 %T.%N" -r "$f")" "$f"; doneNote that this can mess with DST and timezone.
An alternative might be to add %z at end of date string, or add -u to date options.
TZ=UTC0 touch -d "$(date -u +"2014-05-25 %T.%N" -r "$f")"Test
Test, test, test before action. Check with ls --full-time, echo instead of touch etc. find ... -printf also have time/date options.
You could even do a backup of times to a text file.Notes:
From Q:1969 days ago is 29 Sep 2010.
1969 days into the future is Jul 11 2021 (at least in my time zone).
To get May 25 2014 from "-1969 days ago" current date has to be 15 Oct 2019. The issue with "-1969 days ago" is that you have a minus in front of the time.
Minus + minus = plus
Either remove the minus sign, or remove the ago part.
1969 days ago is 29 Sep 2010, as is -1969 days
|
I have about 100 .jpeg images that I would like to change the file time stamp for. I have seen many examples of using touch to modify the time stamp based on the number of days, hours, etc., but those do not work in my situation.
I have attempted to use touch -d "-1969 days ago" on one of the files, but the new time was way off -- Jul 10 2021 rather than May 25 2014.
Is there any way to change all file time stamps in a directory to a specific date (2014-05-25) while keeping the time portion (2:30 PM in the example below) of the date time stamp?
For example, 2009-01-02 02:30 PM change timestamp to 2014-05-25 2:30 PM.
Thank you.
| Change time stamp to specific date keeping existing time |
Great question. Unfortunately, there doesn't seem to be a documented answer.
The file kind is said to be a "tag", and seems to be a metadata element related to the kMDItemKind field. Its primary purpose seems to be for classifying search results from Spotlight.
But perhaps the most relevant answer to your question is that there is no "why": The file kind tag is not created by touch, but by some other process that Apple has chosen not to disclose. Your results (which are repeatable) are prima facie evidence that - at least in the case of files created by touch - the kind tag is an arbitrary artifact of Apple's process with no relationship to the file created.
|
On macOS I am running a shell script that uses touch to create an empty file without an extension. The files created using the same script randomly have different Kinds, i.e. "Document", "Unix executable", "TextEdit.app Document" with no apparent differences between them. No extended attributes
/usr/bin/touch /Volumes/SDrive/complete/.hashes/"${1}"___"${9}"variables contain text...
example filename:
"NOVA.S48E14.Particles.Unknown.720p.WEB.h264___221a636b1f174def7a72d90a9c9d4e9af6aab6ee"
I am curious why an empty file with no extension would be interpreted to be anything other than Kind "Document" when created with the touch command, and if there is a method to specify without using an extension?
I have not been able to test this on any other OS.
| Why does using touch, to create an empty file with no filetype, create various kinds of files? |
There's the install command from GNU coreutils with the -D option which can copy a file and create the directories leading to them in one go (and also let you specify the ownership and permissions). By default, it creates executable files and doesn't honour the umask as it's typically used as a dev tool in make install stages.
install -m u=rw,go=r -D /dev/null some/new/file(the permissions of the directory components it creates are always u=rwx,go=rx).
Or you could always implement it as a create Zsh function such as:
create() {
local file ret=0
for file do
mkdir -p -- "$file:h" && true >> "$file" || ret=$?
done
return "$ret"
}Though creating an empty regular file seems a bit pointless to me.
Generally, you'd do:
mkdir -p some/dir
your-editor some/dir/some-fileTo create some-file (the file would be created as soon you save it (with actual content) in your editor).
Or any other command that creates some content like:
some-command > some/dir/some-file
wget -o some/dir/some-file https://example.com/whatever
cp source some/dir/some-file
...etc. |
I am curious whether it is possible to create a directory and file inside this directory with one command, similar to mkdir -p but for a text file and intermediate directory.
I read through the touch manual and found nothing.
Neither I could find the answer on unix stackexchange.
Is there any way to do so (perhaps without using other command rather than touch), since it is pretty routine task to initiate a new directory with a file?
| Zsh: How to create a directory and file inside it with one command? |
If you always use the same usb socket for a touchscreen, you might be able to convert the id used by xinput for a device to the fixed "path" of the device on the usb bus. Use xinput list to find the 2 ids of the touchscreens by name. Then use xinput list-props on each id and look for the Device Node, eg:
$ xinput list-props 12 | grep 'Device Node'
Device Node (282): "/dev/input/event6"Then use udevadm info on that path /dev/input/event6 and look for the DEVPATH or some line that is different between the 2 touchscreens and does not change, eg:
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.4/2-1.4.3/2-1.4.3:1.0/0003:1111:9999.0005/input/input6/event6This path shows where on the bus the events come from. Just some part, such as 2-1.4.3 should be unique enough to identify the usb socket.
(If you are lucky, the touchscreens might have some unique serial number that could be shown in this output).
Here's a few lines of bash to experiment with:
name='The Touchscreen Name'
ids=$(xinput --list |awk -Fid= "/$name/"'{print $2+0}')
for id in $ids
do event=$(xinput list-props "$id" | awk -F'"' '/Device Node/{print $2}')
path=$(udevadm info "$event" |
awk -F/ '/DEVPATH=/{printf "%s %s %s\n",$7,$8,$9}')
echo "$id $path"
done |
on my Linux box I have 2 DELL touch display of the exact same type. One is connected on HDMI-2, the other on DP-1. To map the touch display I use
sudo xinput --map-to-output _ID1_ HDMI-2
sudo xinput --map-to-output _ID2_ DP-2problem is every time I disconnect and reconnect the USB of touch device the ID changes...typically it inverts between ID1 and ID2 thus inverting touch on the two display. I need a way to be sure of the ID assigned to each monitor. Is there a way to track some property unique to the monitor to recognize them ?
Thanks
Lorenzo
| Map touch display of the same type with xinput - which is which |
What you see in the ls listing are the "traditional" permission bits, all you'd have in a system that doesn't support ACLs, and all that can be used by tools (or users!) that aren't ACL-aware.
The "traditional" group permission bits don't correspond to the owning group ACL, but to the ACL mask (acl(5) man page):CORRESPONDENCE BETWEEN ACL ENTRIES AND FILE PERMISSION BITS
The permissions defined by ACLs are a superset of the permissions
specified by the file permission bits.
There is a correspondence between the file owner, group, and other
permissions and specific ACL entries: the owner permissions
correspond to the permissions of the ACL_USER_OBJ entry. If the ACL
has an ACL_MASK entry, the group permissions correspond to the
permissions of the ACL_MASK entry. Otherwise, if the ACL has no
ACL_MASK entry, the group permissions correspond to the permissions
of the ACL_GROUP_OBJ entry. The other permissions correspond to
the permissions of the ACL_OTHER entry.What the mask does, is limit the permissions that can be granted by ACL entries for named users, named groups, or the owning group. In a way, you can think of the three sets of "traditional" permission bits as applying to 1) the owning user, 2) other explicitly defined users (without ACLs: members of a the owning group; with ACLs: those plus other named users or members of other named groups), and 3) everyone else.
The practical reasoning there is that if a user or program wants to make sure only the owner has write permissions to the file, something like chmod go-w still works to do that, even without the actor knowing about ACLs.
So, having it show rwx for the group in the ls listing is by design, since you have the user:zigbee2mqtt:rwx and user:stack:r-x ACL entries there. The ls output just hints that there are some others apart from the owning user who have read, write and/or execute permissions on the file. Setting the mask to 000 (with e.g. chmod g-rwx or the appropriate setfacl command) would make those ACL entries for user:zigbee2mqtt and user:stack ineffective.When you create a file with touch, and see mask::rw- on it, that's because touch and most other tools create regular files with permissions 0666, not 0777, leaving the x bits off. Most files shouldn't be executable. Regardless of the ACLs, the permissions passed to the open() system call still count, the same as if the permissions were changed with chmod(). Apart from leaving the x bits off, this allows a program to create private files by setting the permissions bits to 0600.
|
I am pretty sure it is a stupid mistake but I can't seem to figure it out by myself, so please have a look.
I set up an ACL for the current folder like so:
zigbee2mqtt@nuc:/tmp/folder$ getfacl .
# file: .
# owner: zigbee2mqtt
# group: zigbee2mqtt
user::rwx
user:stack:r-x
user:zigbee2mqtt:rwx
user:milkpirate:rwx
group::---
mask::rwx
other::---
default:user::rwx
default:user:stack:r-x
default:user:zigbee2mqtt:rwx
default:user:milkpirate:rwx
default:group::---
default:mask::rwx
default:other::---
zigbee2mqtt@nuc:/tmp/folder$ id
uid=978(zigbee2mqtt) gid=977(zigbee2mqtt) groups=977(zigbee2mqtt)so when I now create a folder/file in that folder like so:
zigbee2mqtt@nuc:/tmp/folder$ touch foo; mkdir barIt results in the following permission on the folder foo:
zigbee2mqtt@nuc:/tmp/folder$ getfacl foo
# file: foo
# owner: zigbee2mqtt
# group: zigbee2mqtt
user::rwx
user:stack:r-x
user:zigbee2mqtt:rwx
user:milkpirate:rwx
group::---
mask::rwx
other::---
default:user::rwx
default:user:stack:r-x
default:user:zigbee2mqtt:rwx
default:user:milkpirate:rwx
default:group::---
default:mask::rwx
default:other::---which looks fine so far.
But the ACL of the file then looks off:
# file: bar
# owner: zigbee2mqtt
# group: zigbee2mqtt
user::rw-
user:stack:r-x #effective:r--
user:zigbee2mqtt:rwx #effective:rw-
user:milkpirate:rwx #effective:rw-
group::---
mask::rw-
other::---I would expect the mask to be rwx (desired).
Since group and other are --- (desired) the permission in ls -la to be the same, but they are:zigbee2mqtt@nuc:/tmp/folder$ ls -la
total 20
drwxrwx---+ 3 zigbee2mqtt zigbee2mqtt 4096 Jan 15 17:55 .
drwxrwxrwt 16 root root 4096 Jan 15 17:59 ..
-rw-rw----+ 1 zigbee2mqtt zigbee2mqtt 0 Jan 15 17:55 bar
drwxrwx---+ 2 zigbee2mqtt zigbee2mqtt 4096 Jan 15 17:55 foobut I would expect (and desire):
zigbee2mqtt@nuc:/tmp/folder$ ls -la
total 20
drwxrwx---+ 3 zigbee2mqtt zigbee2mqtt 4096 Jan 15 17:55 .
drwxrwxrwt 16 root root 4096 Jan 15 17:59 ..
-rw-------+ 1 zigbee2mqtt zigbee2mqtt 0 Jan 15 17:55 bar
drwx------+ 2 zigbee2mqtt zigbee2mqtt 4096 Jan 15 17:55 fooEDIT:
Ok, did some testing and all seems to work as desired, the result of ls -la does not seem to reflect the correct rights:
zigbee2mqtt@nuc:/tmp/folder$ sudo -u nginx -g zigbee2mqtt bash
nginx@nuc:/tmp/folder$ ls
ls: cannot open directory '.': Permission denied | touch/mkdir seems to ignore default ACL |
Your problem stems from capturing all of the ls output into a single (string) variable named files. The variable looks something like:
filename1\nfilename2\nfilename3\n...See for yourself with:
echo "$files" | od -cWhat you're really doing is looping once over a really long string that corresponds to a file that doesn't exist. The error you got was slightly informative -- it's telling you that this long string-of-a-filename doesn't exist.
To touch every file in a directory, just use shell globbing and run touch (the glob would only take files in that one directory):
touch node_modules/suman-types/dts/*or touch them one by one:
for file in node_modules/suman-types/dts/*; do touch "$file"; doneor use find to find all files recursively within the directory, and have it run touch on them:
find node_modules/suman-types/dts -type f -exec touch -- {} \;or in shells that support it (Bash/ksh/zsh, with some variations), use the recursive glob operator **:
shopt -s globstar # in Bash
for file in node_modules/suman-types/dts/**/*; do
touch "$file"
done |
I want to touch each file in a directory:
files=$(ls -a "node_modules/suman-types/dts")echo "files $files";for file in "$files"; do
echo "touching file $file";
touch "node_modules/suman-types/dts/$file";
donebut after running that, I get:
inject.d.ts
injection.d.ts
integrant-value-container.d.ts
it.d.ts
reporters.d.ts
runner.d.ts
suman-utils.d.ts
suman.d.ts
table-data.d.ts
test-suite-maker.d.ts
test-suite.d.ts: File name too longWhat is that "File name too long" message about?
Update #1
I changed my script to this:
files=$(find "node_modules/suman-types/dts" -name "*.d.ts")for file in "$files"; do
echo "touching file $file";
touch "$file";
donetouch "node_modules/suman-types"But then I get this:
$ ./types-touch.sh
touching file node_modules/suman-types/dts/after-each.d.ts
node_modules/suman-types/dts/after.d.ts
node_modules/suman-types/dts/before-each.d.ts
node_modules/suman-types/dts/before.d.ts
node_modules/suman-types/dts/describe.d.ts
node_modules/suman-types/dts/global.d.ts
node_modules/suman-types/dts/index-init.d.ts
node_modules/suman-types/dts/inject.d.ts
node_modules/suman-types/dts/injection.d.ts
node_modules/suman-types/dts/integrant-value-container.d.ts
node_modules/suman-types/dts/it.d.ts
node_modules/suman-types/dts/reporters.d.ts
node_modules/suman-types/dts/runner.d.ts
node_modules/suman-types/dts/suman-utils.d.ts
node_modules/suman-types/dts/suman.d.ts
node_modules/suman-types/dts/table-data.d.ts
node_modules/suman-types/dts/test-suite-maker.d.ts
node_modules/suman-types/dts/test-suite.d.ts
touch: node_modules/suman-types/dts/after-each.d.ts
node_modules/suman-types/dts/after.d.ts
node_modules/suman-types/dts/before-each.d.ts
node_modules/suman-types/dts/before.d.ts
node_modules/suman-types/dts/describe.d.ts
node_modules/suman-types/dts/global.d.ts
node_modules/suman-types/dts/index-init.d.ts
node_modules/suman-types/dts/inject.d.ts
node_modules/suman-types/dts/injection.d.ts
node_modules/suman-types/dts/integrant-value-container.d.ts
node_modules/suman-types/dts/it.d.ts
node_modules/suman-types/dts/reporters.d.ts
node_modules/suman-types/dts/runner.d.ts
node_modules/suman-types/dts/suman-utils.d.ts
node_modules/suman-types/dts/suman.d.ts
node_modules/suman-types/dts/table-data.d.ts
node_modules/suman-types/dts/test-suite-maker.d.ts
node_modules/suman-types/dts/test-suite.d.ts: No such file or directory | I get message "File name too long" when running for..in and touch |
So, here:
printf "file%c%d " {A..Z}{1..100}The brace expansion produces strings like A1, A2, A3... Z99, Z100. Then printf tries to match those to the format specifiers %c and %d, using the first for %c, second for %d, third for %c again, etc.
But %d expects a number and A2 isn't one, so there's an error.
%c%d would expect arguments like A, 1, A, 2..., as distinct arguments, but that would be hard to generate with brace expansion.
Since the brace expansion already combines the letter and number sequences, you can just use printf "file%s " {A..Z}{1..100} to use the results of the expansion as-is. Or even just echo file{A..Z}{1..100}.
Or the even more direct version pLumo's answer has.
|
I am trying to create a series of files with brace expansions. I want create the files fileA1 to fileZ100 with all possible combinations (Something like touch file[A..Z][1..100]).
If I run the command touch $(printf "file%d " {1..100}) the output is ok:
file1 file15 file21 file28 file34 file40 file47 file53 file6 file66 file72 file79 file85 file91 file98
file10 file16 file22 file29 file35 file41 file48 file54 file60 file67 file73 file8 file86 file92 file99
file100 file17 file23 file3 file36 file42 file49 file55 file61 file68 file74 file80 file87 file93
file11 file18 file24 file30 file37 file43 file5 file56 file62 file69 file75 file81 file88 file94
file12 file19 file25 file31 file38 file44 file50 file57 file63 file7 file76 file82 file89 file95
file13 file2 file26 file32 file39 file45 file51 file58 file64 file70 file77 file83 file9 file96
file14 file20 file27 file33 file4 file46 file52 file59 file65 file71 file78 file84 file90 file97The same if I run touch $(printf "file%c " {A..Z}):
fileA fileC fileE fileG fileI fileK fileM fileO fileQ fileS fileU fileW fileY
fileB fileD fileF fileH fileJ fileL fileN fileP fileR fileT fileV fileX fileZI'm trying to combine them touch $(printf "file%c%d " {A..Z}{1..100}), but the output is:
[...]
-bash: printf: Y2: invalid number
-bash: printf: Y4: invalid number
-bash: printf: Y6: invalid number
-bash: printf: Y8: invalid number
-bash: printf: Y10: invalid number
-bash: printf: Y12: invalid number
-bash: printf: Y14: invalid number
-bash: printf: Y16: invalid number
-bash: printf: Y18: invalid number
-bash: printf: Y20: invalid number
-bash: printf: Y22: invalid number
-bash: printf: Y24: invalid number
-bash: printf: Y26: invalid number
-bash: printf: Y28: invalid number
-bash: printf: Y30: invalid number
-bash: printf: Y32: invalid number
-bash: printf: Y34: invalid number
-bash: printf: Y36: invalid number
-bash: printf: Y38: invalid number
-bash: printf: Y40: invalid number
-bash: printf: Y42: invalid number
-bash: printf: Y44: invalid number
-bash: printf: Y46: invalid number
-bash: printf: Y48: invalid number
-bash: printf: Y50: invalid number
-bash: printf: Y52: invalid number
-bash: printf: Y54: invalid number
-bash: printf: Y56: invalid number
-bash: printf: Y58: invalid number
-bash: printf: Y60: invalid number
-bash: printf: Y62: invalid number
-bash: printf: Y64: invalid number
-bash: printf: Y66: invalid number
-bash: printf: Y68: invalid number
-bash: printf: Y70: invalid number
-bash: printf: Y72: invalid number
-bash: printf: Y74: invalid number
-bash: printf: Y76: invalid number
-bash: printf: Y78: invalid number
-bash: printf: Y80: invalid number
-bash: printf: Y82: invalid number
-bash: printf: Y84: invalid number
-bash: printf: Y86: invalid number
-bash: printf: Y88: invalid number
-bash: printf: Y90: invalid number
-bash: printf: Y92: invalid number
-bash: printf: Y94: invalid number
-bash: printf: Y96: invalid number
-bash: printf: Y98: invalid number
-bash: printf: Y100: invalid number
-bash: printf: Z2: invalid number
-bash: printf: Z4: invalid number
-bash: printf: Z6: invalid number
-bash: printf: Z8: invalid number
-bash: printf: Z10: invalid number
-bash: printf: Z12: invalid number
-bash: printf: Z14: invalid number
-bash: printf: Z16: invalid number
-bash: printf: Z18: invalid number
-bash: printf: Z20: invalid number
-bash: printf: Z22: invalid number
-bash: printf: Z24: invalid number
-bash: printf: Z26: invalid number
-bash: printf: Z28: invalid number
-bash: printf: Z30: invalid number
-bash: printf: Z32: invalid number
-bash: printf: Z34: invalid number
-bash: printf: Z36: invalid number
-bash: printf: Z38: invalid number
-bash: printf: Z40: invalid number
-bash: printf: Z42: invalid number
-bash: printf: Z44: invalid number
-bash: printf: Z46: invalid number
-bash: printf: Z48: invalid number
-bash: printf: Z50: invalid number
-bash: printf: Z52: invalid number
-bash: printf: Z54: invalid number
-bash: printf: Z56: invalid number
-bash: printf: Z58: invalid number
-bash: printf: Z60: invalid number
-bash: printf: Z62: invalid number
-bash: printf: Z64: invalid number
-bash: printf: Z66: invalid number
-bash: printf: Z68: invalid number
-bash: printf: Z70: invalid number
-bash: printf: Z72: invalid number
-bash: printf: Z74: invalid number
-bash: printf: Z76: invalid number
-bash: printf: Z78: invalid number
-bash: printf: Z80: invalid number
-bash: printf: Z82: invalid number
-bash: printf: Z84: invalid number
-bash: printf: Z86: invalid number
-bash: printf: Z88: invalid number
-bash: printf: Z90: invalid number
-bash: printf: Z92: invalid number
-bash: printf: Z94: invalid number
-bash: printf: Z96: invalid number
-bash: printf: Z98: invalid number
-bash: printf: Z100: invalid numberSo... what is the correct regular expression? Should I use pipes?
| Create multiples files with brace expansion combining letters and numbers |
When a pattern such as abc* is used unquoted in the shell, the shell will try to match it against the available filenames (this is called "filename generation" but is often referred to as "globbing"). If it fails to match any filename, most sh-like shells will leave the pattern unexpanded and pass it to the utility as is.
Example:
$ touch xyz
$ touch abc*
$ tree
.
|-- abc*
`-- xyz0 directory, 2 files$ touch xyz*
$ tree
.
|-- abc*
`-- xyz0 directory, 2 filesThe touch xyz* command did not create a file called xyz*, because the filename xyz matched the pattern. The touch utility was therefore called with the xyz filename.
In the bash shell, setting the failglob shell option with shopt -s failglob will make the shell complain if a shell glob does not match anything:
$ shopt -s failglob
$ touch 123*
bash: no match: 123*The equivalent option is turned on by default in the zsh shell.
Setting the nullglob shell option in bash (or NULL_GLOB in zsh) would make the pattern disappear if it doesn't match a filename:
$ shopt -s nullglob
$ touch fo*
usage: touch [-acm] [-d ccyy-mm-ddTHH:MM:SS[.frac][Z]] [-r file]
[-t [[cc]yy]mmddHHMM[.SS]] file ...(we get an error from touch since it was called without any arguments)
To guarantee that the pattern is used as a string (as it is), and not used for globbing, you should quote it:
$ touch "file*"
$ touch "file**"
$ touch "file***"
$ tree
.
|-- file*
|-- file**
`-- file***0 directory, 3 filesNot quoting the filenames in this example would have given you only one file called file* (if the directory was initially empty), since the file** and file*** patterns matches that first file* name.
|
For example, in rm -r abc* "*" means any string. However, if we use it in touch abc* abcd* abcde* (and we don't have any files in directory starting with abc or abcd or abcde) "*" means just a symbol, and files abc* abcd* abcde* will be created. If after that we will use touch -m ab* the modification time of files abc* abcd* abcde* will be changed.
Why in some cases "*" means any string, and in some cases it is just a symbol? how the computer know when to change it's meaning?
| Why "*" works differently in different commands? |
Thanks to steeldriver for his comment, it guided me to the answer.
The pipe operator only works when the command accepts arguments from stdin, in this case commands like touch or rm does not, an alternative solution is to use command sustitution as in the example
touch $(echo {1..3})Or by using the xargs which converts input from standard input into arguments to a command, hence is possible to do
echo {1..3} | xargs touchas simple as that
| Testing with the linux command line and pipe I tried to do echo {1..3} | touch and it doesn't work. I achieved the results with touch $(echo {1..3}).
Why I can't pass the list generated by echo to touch using the pipe as in the first example?
| Pipe vs Command substitution [duplicate] |
In the shell:
for f in ./IMG_*.jpg ; do
t=${f##*/}
touch "$f" -t "${t:4:8}${t:13:4}.${t:17:2}"
doneBash, ksh, zsh etc have the ${var:n:m} substring expansion, and if you need to do it recursively, enable globstar and use **/IMG_*.jpg instead.
Doing it with find needs the shell, too:
$ find -name "IMG_*.jpg" -exec bash -c '
for f; do t=${f##*/}; touch "$f" -t "${t:4:8}${t:13:4}.${t:17:2}" ; done
' sh {} \+The first argument to Bash after the script goes to the $0 variable, which usually contains the shell name. The rest go to the positional parameters $1, $2, etc. and for f or for f in "$@" loops over them.
The construct is here is rather common (at least in unix.SE answers).
The main part of the loop here is the same as in the first example.The find command in your question find .. -exec touch -t"$(...)" {} \; doesn't work since the command substitution is in double quotes, so it gets expanded before find runs. The {} is piped literally to awk, and it just so happens that the awk script only prints a dot.
If you did put the command substitution in single quotes, it would be passed to touch as-is (find would only substitute {}). touch would get the argument -t$(echo ...), dollar signs, parenthesis and all. find doesn't run the command through the shell by itself, we need to explicitly do it, as above.
In single quotes example:
$ find -name x -exec echo 'hello $(foo {})' \;
hello $(foo ./x) |
I have a lot of files where filename contains file creation date (IMG_YYYYMMDD_hhmmss.jpg):
IMG_20171015_133516.jpg
IMG_20171015_133827.jpg
IMG_20171015_142634.jpg
IMG_20171015_142834.jpg
IMG_20171015_142857.jpgbut actual file creation date is different. I need to set it back to date from a filename.
I know how to change the date of all files to current date:
find -type f -exec touch {} \;and how to parse the file name to get the date in the proper format for touch -t
echo IMG_20171015_133516.jpg | awk -F_ '{print $2 substr($3,0,4) "." substr($3,5,2)}'
201710151335.16But I have no idea how to combine these commands together to change all files.
find -type f -exec touch -t"$(echo '{}' | awk -F_ '{print $2 substr($3,0,4) "." substr($3,5,2)}')" {} \;returnstouch: invalid date format ‘.’ | Set file modification date from date stored as filename |
You have so many files in /tmp that you can't fit all the names on the command line at once (the version you have is also unsafe if any paths have whitespace in them).
The good news is that find can do this for you safely and correctly:
find /tmp -exec touch -c '{}' +will find all the files as before, and then run touch as many times as necessary with as many files as will fit each time.
find's -exec option takes a command to run for matched files and substitutes the paths where {} is. + means it runs the command with many files at once, or \; would run touch once for each file.As noted in the comments, -execdir touch -c '{}' \; is strictly safer here, although it will likely be quite a bit slower, and there's not much benefit to be had on a single-user system. It avoids certain race conditions by switching into each subdirectory first, and then running the command only for files in that directory each time. The -execdir option is a non-standard extension, but it is supported in GNU, FreeBSD, OpenBSD, NetBSD, and OS X finds; the other commercial Unices generally don't have it. I'm not sure what you're using, but take the above into account if it's applicable.
|
I have written a shell script to touch all the files in the /tmp directory. However, there was an error message saying that
/bin/touch: Argument list too long.
What's the cause of the problem?
#!/bin/bashdayNo=1
while test $dayNo -le 200
do
touch `find /tmp/`
sleep 86000
done | shell script for auto-touching files |
The simplest : you could use :
touch -r Referencefile THEFILE to give THEFILE the same time as Referencefile
so:
rm -f Referencefile
echo > Referencefile #to set the creation time
#...do your captures here, then concatenate into THEFILE ....
echo >> Referencefile #to set the modification time
touch -r Referencefile THEFILEBut if you prefer to have a more flexible way:
To have a "reliable" way to get the time of a file in a "portable" format, not depending on if the file last changed within 6 months, etc:
tar cf - file | tar tvf -so you could do this to get a time suitable for touch:
gettouchdate () {
tar cf - "$1" | tar tvf - | tr ':' ' ' \
| awk '{mm=sprintf("%02d",(match("JanFebMarAprMayJunJulAugSepOctNovDec",$5)+2)/3) ;
print $10 mm $6 $7 $8 $9 ;}'
}
#firstdate=$(gettouchdate "/path/to/FIRSTFILE")
lastdate=$(gettouchdate "/path/to/LASTFILE")
touch -r /path/to/FIRSTFILE THEFILE
touch -m "$lastdate" THEFILE |
I have created a script to read 15 pcap files from a folder and merge then into one file using mergecap command. I want the merged file to have the creation time same as the first file of the 15 files and the last modified time same as the last 15th file. W.R.T Changing a file's "Date Created" and "Last Modified" attributes to another file's
I have got how to modify the file times, but this will change all file times to that of the first file. touch -m command needs to be used here , but I cant see how to save the last modified time from the last file and put this to to the merged file.
| Updating last modified time of a file |
(Using set -x (xtrace) to see the command that actually runs)
$ set -x
$ touch #a{1..10}
+ touch
touch: missing file operand
Try 'touch --help' for more information.
$ touch a{1..10}
+ touch a1 a2 a3 a4 a5 a6 a7 a8 a9 a10The hash sign # at the start of a word makes the rest of the line a comment. You need to quote it:
$ touch "#"a{1..10}
+ touch '#a1' '#a2' '#a3' '#a4' '#a5' '#a6' '#a7' '#a8' '#a9' '#a10'Or in Bash, you can use shopt -u interactive_comments to disable processing comments altogether.
|
My system is
Kernel: 5.3.0-26-generic x86_64 bits: 64 Desktop: Cinnamon 4.4.8 Distro: Linux Mint 19.3 Tricia Touch version is touch (GNU coreutils) 8.28
When the following command is given -
$ touch #a{1..10}It says -
touch: missing file operand
Try 'touch --help' for more information.What is the issue here?
| touch: missing file operand with filename containing hash # |
try
for file in *"$foobar"*
do
dest="$(echo $file| sed -e 's/\(.*\)\.[^\.]*$/\1.csv/' )"
if test -f "$file"
then
/home/user/scriptModelise.pl "$file" >> /home/user/Documents/collectCSV/$dest
else
echo "no $foobar file"
fi
donewhere\(.*\)\.[^\.]*$ capture a pattern with any char, (end of pattern) followed by a dot, non dot till end of line
\1.csv insert pattern found, add .csv
*"$foobar"* will expand to litteral *foobar* (with proper value) if no matching file are found. hence the need for test -f "$file" Edit:\(.*\)\.[^\.]*$ (left hand side: finding pattern(s) )split into ( _ are place holder )__.*__________ a pattern with any char (dot has a special meaning: any char)
__.*__\._______ a pattern with any char, followed by a dot (escaped dot is a plain dot)
__.*__\.[^\.]*$ pattern with any char, (end of pattern) followed by a dot, non dot ([^\.]*) till end of line (dollar sign is special for end of line)
\(__\)__________ capture the first part of pattern.
\1.csv (right hand side, what to do)
\1____ \1 match what was within first \( \) , \2 for second and so on, use & for whole pattern. |
I'm trying to create a script that can:look for a file containing "foobar" as name
a script is executed on this file and the output must be stored in a new CSV file, which is created automatically and which has the same name as the searched file. The only difference is that the extension is changed to CSV.This is my script. :
#!/bin/bash# search for file containing "foobar" as a name in the directory
for file in /home/user/Documents/* ;
do if [[ "$file" == *"$foobar"* ]]; then
touch /home/user/Documents/collectCSV/csv1.csv
# executing script of modelising foobar file ==> extract some data from $foobar file and insert it in the
# created file csv1.csv
/home/user/scriptModelise.pl $file >> /home/user/Documents/collectCSV/csv1.csvelse
echo "foobar file not found"
fidoneThe problem is that this method of creating a file is static. I didn't succeed in making the file creation automatic. I mean when it finds a foobar file it will be modelised in a new file that will be created.
Any help please ?
| how to create a file automatically? |
How about:
#!/bin/bashfor file in *; do
# Get the access time using stat
dateString=$(stat --format %x "$file")
# Use the datestring to update the time with the
# access time
touch -d "$dateString" "$file"
doneFrom man stat:
%x time of last access, human-readable |
I have a bunch of files in a directory where the modification time was changed (incorrectly) with touch -m
The access time of these files is still close enough to what the modification time was, so I'd like to change them back.
Is there a way of doing a touch where it sets the mtime = atime? I don't want to set them all to the same timestamp, but I want to go file-by-file setting mtime = atime.
| Changing file modification time to access time in bulk |
-exec touch {} \;or better yet the modern xargs-style
-exec touch {} +as ; otherwise is used by the shell for conflicting purposes.
| I'm using Amazon Linux with bash shell. I'm trying to touch every file in a certain directory, but this command is failing:
[myuser@mymachine scripts]$ find /usr/java/jboss/standalone/deployments/myapp.war -type f -exec touch '{}' ;
find: missing argument to `-exec'How do I correct the above?
| How do I touch every file in a directory? [duplicate] |
Your file ~/.zshrc is a symbolic link to a name in a directory that does not exist. This means appending to the file will fail in the way you show, and touching the file will also fail similarly.
To resolve this, you may either try to recreate the correct symbolic link or remove the broken one and replace it with an actual regular file.
To recreate ~/.zshrc as a symbolic link to the correct pathname, figure out where it is supposed to be pointing to, then use
ln -s -f ~/the/correct/path/zshrc ~/.zshrc(Unfortunately, I can't tell what the correct pathname is supposed to be.)
To remove the broken link, use
rm ~/.zshrcYou may then append the alias definition to the end of the file with the echo command as you initially tried to do.
|
I'm on macOS Ventura 13.2.
Tried to fix python by adding it to .zshrc:
echo "alias python=/usr/bin/python3" >> ~/.zshrc
zsh: no such file or directory: /Users/username/.zshrcSeems like the file is gone, so I attempted to recreate it:
touch ~/.zshrc
touch: /Users/username/.zshrc: No such file or directoryNo luck. What is going on? How might I fix this?
| touch: /Users/username/.zshrc: No such file or directory |
Assuming you just want the immediately directories and not all nested sub directories.
The following assumes you are currently in the same directories and the directories you want to loop over
for dir in *; do
[ -d "$dir" ] && touch -- "$dir/$dir.txt"
doneThis will loop over every file in the current directory
filter for
directories (including symlinks to directories).
And then create the requested file in the specified
directoryAlso you may be interested in shellcheck which point out common errors/bad practices (like the use of ls in this case)
|
I need to create a script to scan folders in a directory and take the name of each folder, make a .txt file, name it with the name of the folder and put inside that folder.
For example:
A directory that has 3 folders in it named "1" "2" and "3"
I want to create a .txt file in each folder named with the name of that folder
so that folder 1 has "1.txt" in it
folder 2 has "2.txt" in it
etc..
I managed to do that with this script:
for i in $(ls -d */); do touch "$i $(basename $i).txt" ; done
The problem is I want to do the same thing but with folders that has spaces in their names.
For example:
If I have a folder named "Test Me"
It will give an error saying something like this:
Me: no directory with that name
It will see only the word "Me" and treat it as a folder and not "Test Me" as a whole.
How can I do that ?
Update
This is the solution, it is commented below by TAAPSogeking (Thanks again to him)
for dir in *; do [ -d "$dir" ] && touch "$dir/$dir.txt"; done
| How to make a for loop to read directory names with spaces in them? |
With the GNU implementation of xargs, you can specify newline as the separator with the -d/--delimiter option:
xargs --no-run-if-empty --delimiter='\n' --arg-file=file.txt touch --With short options:
xargs -r -d '\n' -a file.txt touch -- | I would like to create files from the following list.
There is no problem if the list doesn't have a space ... but the problem is it has a space
user@linux:~$ cat file.txt
Apples
Bing Cherry
Crab Apples
Dragon Fruit
user@linux:~$ Before
ser@pc:~$ ls -l
total 4
-rw-r--r-- 1 user user 44 Jun 9 14:06 file.txt
user@linux:~$ xargs touch
user@linux:~$ cat file.txt | xargs touch
user@linux:~$ Instead of creating Apples, Bing Cherry, Crab Apples, Dragon Fruit, the command producing these output.
After
user@linux:~$ ls -l
total 4
-rw-r--r-- 1 user user 0 Jun 9 14:11 Apples
-rw-r--r-- 1 user user 0 Jun 9 14:11 Bing
-rw-r--r-- 1 user user 0 Jun 9 14:11 Cherry
-rw-r--r-- 1 user user 0 Jun 9 14:11 Crab
-rw-r--r-- 1 user user 0 Jun 9 14:11 Dragon
-rw-r--r-- 1 user user 44 Jun 9 14:06 file.txt
-rw-r--r-- 1 user user 0 Jun 9 14:11 Fruit
user@linux:~$ What should I do to handle space in this situation?
| How to create files from a list which contain space [duplicate] |
From the GNU touch documentation:touch changes the access and/or modification timestamps of the specified files.So, if the file exists, then touch modifies it's timestamps. We can check this:
$ stat .
File: '.'
Size: 40 Blocks: 0 IO Block: 4096 directory
Device: 11h/17d Inode: 2338759 Links: 2
Access: (0755/drwxr-xr-x) Uid: ( 1000/ chronos) Gid: ( 1000/ chronos)
Context: u:object_r:tmpfs:s0
Access: 2018-10-29 08:06:16.918056344 +0530
Modify: 2018-10-29 08:06:15.484056316 +0530
Change: 2018-10-29 08:06:15.484056316 +0530
Birth: -Now we run touch . and then:
$ stat .
File: '.'
Size: 40 Blocks: 0 IO Block: 4096 directory
Device: 11h/17d Inode: 2338759 Links: 2
Access: (0755/drwxr-xr-x) Uid: ( 1000/ chronos) Gid: ( 1000/ chronos)
Context: u:object_r:tmpfs:s0
Access: 2018-10-29 08:06:29.131056579 +0530
Modify: 2018-10-29 08:06:29.131056579 +0530
Change: 2018-10-29 08:06:29.131056579 +0530
Birth: -Note how the Access:, Modify: and Change: fields have changed.
|
I have searched for a similar question here, but found nothing related.
In Linux, the dot (.) refers to the directory itself. The touch command creates a file, if it does not exist.
But what does touch . (dot as argument) do?
I have checked the GNU touch documentation and the LINFO information about dot, but found nothing related.
I have tried this command in my Fedora and it seems that nothing is changed.
| In Linux, what does "touch ." (touch dot) do? |
This is a straightforward file modification time check; the complications mainly arise from the possibility of up to 86,400 alerts per day (usually over a long holiday weekend is when these sorts of thing break), and additional complications of whether or not the modification time checker (or cron, or the system...) are actually running, whether the host clock is correct (time skew on virts, BIOS clock coming up four years in the future, broken NTP, etc).
#!/bin/sh# what we're checking for mtime changes straying from the current system time
MONITOR=foofile
THRESHOLD=60# use mtime on this file to avoid frequent alert spam should the above stop
# being updated
LAST_ALERT=barfile
LAST_ALERT_THRESHOLD=60NOW_MTIME=`date +%s`absmtimedelta() {
delta=`expr $NOW_MTIME - $1`
# absolute delta, in the event the mtime is wrong on the other side of
# the current time
echo $delta | tr -d -
}alertwithlesscronspam() {
msg=$1
if [ ! -f "$LAST_ALERT" ]; then
# party like it's
touch -t 199912312359 -- "$LAST_ALERT"
fi
# KLUGE this stat call is unportable, but that's shell for you
last_mtime=`stat -c '%Y' -- "$LAST_ALERT"`
last_abs_delta=`absmtimedelta $last_mtime`
if [ $last_abs_delta -gt $LAST_ALERT_THRESHOLD ]; then
# or here instead send smoke signals, carrier pigeon, whatever
echo $msg
touch -- "$LAST_ALERT"
exit 1
fi
}if [ ! -r "$MONITOR" ]; then
alertwithlesscronspam "no file alert for '$MONITOR'"
fiMONITOR_MTIME=`stat -c '%Y' -- "$MONITOR"`
ABS_DELTA=`absmtimedelta $MONITOR_MTIME`if [ $ABS_DELTA -gt $THRESHOLD ]; then
alertwithlesscronspam "mtime alert for '$MONITOR': $ABS_DELTA > $THRESHOLD"
fiPerhaps instead consider a standard monitoring framework, which may have support for file modification time checks or a plugin to do so, customizable alerting, metrics, better code than the above, etc.
|
I have set up a very simple script so that I can test whether a process is running or not and if so then it will touch a file and everything will be fine. However if process is not running and file isn't touched then I want to be able to set up an alert.
pgrep "sleep" >/dev/null && touch monitor.log
This script is running in a crontab every minute. I need a way for it to alert if file has not been touched? Is this possible?
Thanks
| Creating alert notification if process stops touching file |
I was able to do it with the following command:
for i in *;do touch -r "$i/"*.nfo
|
I need to do it for over 600 folders with varying names and the .nfo file inside doesn't necessarily have the same name as the folder, he is just a few of them.
m0j0@unity ~/files/TV.TL/TEST $ ls -lr
total 28
drwxrwx--- 2 m0j0 m0j0 162 Nov 30 19:57 G.S01E07.720p.AMZN.WEB-DL
drwxrwx--- 2 m0j0 m0j0 164 Nov 30 19:57 G.S01E07.1080p.AMZN.WEB-DL
drwxrwx--- 2 m0j0 m0j0 148 Nov 30 19:57 G.S01E06.S.1080p.AMZN.WEB-DL
drwxrwx--- 3 m0j0 m0j0 4096 Nov 30 19:57 G.S01E06.HDTV
drwxrwx--- 3 m0j0 m0j0 4096 Nov 30 19:57 G.S01E06.720p.WEB
drwxrwx--- 3 m0j0 m0j0 4096 Nov 30 19:57 G.S01E06.720p.HDTV
drwxrwx--- 3 m0j0 m0j0 4096 Nov 30 19:57 G.S01E05.HDTV
drwxrwx--- 3 m0j0 m0j0 4096 Nov 30 19:57 G.S01E05.720p.WEB
drwxrwx--- 3 m0j0 m0j0 4096 Nov 30 19:57 G.S01E05.720p.HDTV
drwxrwx--- 3 m0j0 m0j0 4096 Nov 30 19:57 G.S01E05.1080p.WEBm0j0@unity ~/files/TV.TL/TEST $ find . -iregex '.*\.\(nfo\)' -printf '%Tc %f\n'
Mon 13 Nov 2017 10:02:05 AM +08 g.s01e06.720p.hdtv.nfo
Wed 22 Nov 2017 08:17:40 AM +08 G.S01E07.1080p.AMZN.WEB-DL.nfo
Wed 22 Nov 2017 08:17:12 AM +08 G.S01E07.720p.AMZN.WEB-DL.nfo
Tue 14 Nov 2017 02:47:07 AM +08 G.S01E06.1080p.AMZN.WEB-DL.nfo
Mon 06 Nov 2017 09:58:54 AM +08 g.s01e05.1080p.web.nfo
Mon 06 Nov 2017 10:01:02 AM +08 g.s01e05.hdtv.nfo
Mon 13 Nov 2017 10:02:23 AM +08 g.s01e06.hdtv.nfo
Mon 06 Nov 2017 09:57:15 AM +08 g.s01e05.720p.web.nfo
Mon 06 Nov 2017 10:01:27 AM +08 g.s01e05.720p.hdtv.nfo
Mon 13 Nov 2017 09:57:36 AM +08 g.s01e06.720p.web.nfo | How to change folder's creation date to match the creation date of the .nfo file inside? |
With no time specified, touch changes the timestamps of all its arguments to the current time at the time each file is touched, which should produce a different timestamp for each file, but in many cases this ends up applying the same timestamp to all its arguments; you can verify this by running stat on all the touched files. They are processed in the order specified on the command line.
To get the result you want, you need to loop and touch each file individually, with some delay:
for file in {1..12}.txt; do touch $file; sleep 0.1; done(with more or less delay depending on the timestamp resolution of the underlying file system).
Note that ls -t lists files sorted by descending timestamp; to see increasing times you need to use ls -rt.
|
I have a list of files that are space separated and I want to use the touch command to update their timestamps in that order. But when I supply the filenames as arguments, the timestamps get updated in a different order.
touch 1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt 10.txt 11.txt 12.txt After running the command above and running ls -t (sorting by time modified) I get the following:
1.txt 10.txt 11.txt 12.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txtDoes supplying arguments to commands not guarantee the execution order? If not, how can I update the timestamps of those files in that specific order?
| Execution order of touch command arguments |
If you look at the man page for touch, you'll see that it takes a filename as an argument. So what you need is:
touch ../cambridge/library/dir_practiceSince you're new to this, let's break this down. A relative pathname is a path specified relative to your current location. Contrast this with an absolute pathname, which starts from the root (/).
So you start at sample_dir/oxford. The first .. takes you back to the sample_dir directory. Then, you want to go to the library directory, which is inside the cambridge directory. Inside the library directory, you want to create the file named dir_practice.
Put all that together, and you get ../ + cambridge/library/ + dir_practice. Together, that's ../cambridge/library/dir_practice. This is the argument we pass to the touch command.
|
I have tried this but it is not working
touch dir_practice ../cambridge/library/
touch dir_practice ./sample_dir/cambridge/library/**** | Issue creating a regular file for a directory |
Yes: you can set the bridge to be VLAN aware.
The bridge will then handle VLAN IDs attached to frames crossing it, including tagging and untagging them according to configuration, and will send a frame belonging to a given VLAN only to ports configured to accept it. This moves all the settings to the bridge itself rather than having to use VLAN sub interfaces (those sub interfaces can still be used in some settings of course).
This feature is not available through the obsolete brctl command, but requires the newer replacement bridge command (along with the usual ip link command). It is a simpler setup (one bridge, no sub-interface).
The method is to configure tap1 as a tagged bridge port with VLAN ID (VID) 5, and eth0 also with VID 5, but set as untagged: output gets untagged, and with this VID as PVID (Port VLAN ID): input gets tagged with it inside the bridge. There can be only one PVID per port.
At the same time optionally remove VLAN ID of 1 assigned by default to each port (unless a more complex setup would require multiple VLANs of course) to keep a clean configuration.
your setup, so far, with newer commands only should look like this:
ip link set eth0 up
ip link set tap1 up# the following line could have directly included at bridge creation the additional parameter `vlan_filtering 1`
ip link add name br0 type bridgeip link set tap1 master br0
ip link set eth0 master br0The specific VLAN aware bridge settings, starting by activating the feature:
ip link set dev br0 type bridge vlan_filtering 1bridge vlan del dev tap1 vid 1
bridge vlan del dev eth0 vid 1bridge vlan add dev tap1 vid 5
bridge vlan add dev eth0 vid 5 pvid untaggedip link set br0 upNote that the bridge's self implicit port is still using VID 1, so assigning an IP directly on the bridge as is done on some settings will now fail to communicate properly. If such configuration is really needed, you can set the bridge's self port in VLAN 5 too, with a slightly different syntax (self) because it's the bridge itself:
bridge vlan del dev br0 vid 1 self
bridge vlan add dev br0 vid 5 pvid untagged selfIt's usually cleaner to (still delete the default VID 1 of the bridge to prevent it from any possible interaction,) add a veth pair, plug one end on the bridge, configure its bridge vlan settings the same as eth0 and assign an IP on the other end.
Good blog series on this topic:Fun with veth-devices, Linux bridges and VLANs in unnamed Linux
network namespaces
I II III IV V VI VII VIII |
I'm trying to set up a system that joins an untagged Ethernet network to a TAP tunnel, adding a VLAN tag as the traffic moves to the tunnel.
So far I have:eth0 - the physical Ethernet interface carrying untagged traffic.
tap1 - the TAP tunnel interface.
br0 - a bridge that contains tap1 (and some other physical interfaces)I know I can add a VLAN tag on the Ethernet side by doing this:
$ ip link add link eth0 name eth0.5 type vlan id 5
$ brctl addif br0 eth0.5But how can I do the reverse?
Edit I've figured out I can do this:
$ ip link add veth0 type veth peer name veth1
$ ip link add link veth0 name veth0.5 type vlan id 5
$ brctl addif br0 veth0.5
$ brctl addbr br1
$ brctl addif br1 eth0
$ brctl addif br1 veth1I think this does what I want - it creates two bridges, with a virtual ethernet device connecting them, and adds/removes the VLAN tag as the traffic passes between the bridges. Is there anything simpler?
| Bridged interfaces and VLAN tags |
Newer versions of scp have the option -3-3
Copies between two remote hosts are transferred through the local host. Without this option the data is copied directly between the two remote hosts |
There are two server that I can access with 2 different VPN connections. I have managed to have both VPN working on the same time on my machine (a bit of routing rules).
I want to do a scp <remote1>:some/file <remote2>:destination/folder from my laptop terminal. But when I try this, the scp command that is invoked on remote1 cannot find remote2 because they are not in the same network. Is it possible to force the scp command to pass through my laptop as a router?
If I try with Nautilus (connect to server, both servers, then copy-paste) it works, but I'd like to do it from a terminal.
| scp between two servers not in the same network |
it seems that disabling NetworkManager did the trick :)
systemctl stop NetworkManager
systemctl disable NetworkManager |
The switch configured on the server (Centos 7) is configured as trunk for VLAN#115,2014.
I have loaded
# lsmod | grep 8021q
# modprobe 8021qI would like to configure an IP address on the server using the VLAN#115
Performing the following configuration:
ifcfg-em1
TYPE=Ethernet
BOOTPROTO=none
DEFROUTE=yes
PEERDNS=yes
PEERROUTES=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
NAME=em1
UUID=c0c4d851-d762-4301-8c20-d6128aee5261
DEVICE=em1
ONBOOT=yesifcfg-em1.115
TYPE=Ethernet
BOOTPROTO=none
IPADDR=172.31.141.242
PREFIX=24
GATEWAY=172.31.141.1
DEFROUTE=yes
PEERDNS=yes
PEERROUTES=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
NAME=em1.115
UUID=c0c4d851-d762-4301-8c20-d6128aee5261
DEVICE=em1.115
VLAN=yes
ONBOOT=yesI ended up being not able to restart the network service.
The error message appearing is :
Failed to start LSB: Bring up/down networking.What am doing wrong ?
| Centos 7: failed to bring up/down networking: configure interface for a trunk interface |
I am not sure what you mean by a GENERAL switch, but for most switches it is impossible to see in which VLAN you are when you are connected to an 'access' port.
That said, using the CDP (Cisco) and LLDP (Juniper) protocols you can find out in which VLAN you are. Enabling CDP/LLDP on an access port is arguably a security risk (information exposure) so it might not be enabled on your network. You can use tcpdump to disassemble CDP/LLDP packets to find the VLAN number.
For Cisco CDP:
sudo tcpdump -nn -v -i eth0 -s 1500 -c 1 'ether[20:2] == 0x2000' For Juniper LLDP:
sudo tcpdump -nn -v -i eth0 -s 1500 -c 1 '(ether[12:2]=0x88cc or ether[20:2]=0x2000)' |
My question: are there any methods to detect that in which vlan I am? Can tcpdump show this? Or can I force a GENERAL switch to say to me?
| In which vlan am I in? |
When using the bridge vlan command, you can add (or delete) a range of VLAN IDs in a single shot. For example:
# bridge vlan add vid 2-4094 dev eth0will add all available VLANs to the trunk interface eth0 (0 and 4095 are reserved in the protocol and must not (nor can) be used, 1 is by default set as PVID untagged VLAN ID, so should be avoided or perhaps better, removed).
# bridge vlan show dev eth0
eth0 1 PVID Egress Untagged
2
3
[...]
4093
4094# bridge -c vlan show dev eth0
port vlan ids
eth0 1 PVID Egress Untagged
2-4094Here -c stands for -c[ompressvlans] rather than -c[olor]: the bridge man page (at least up to iproute2-ss191125) completely lacks information about this option.
Deleting a range works as one could expect:
# bridge vlan del vid 100-200 dev eth0
# bridge -c vlan show
port vlan ids
bridge0 1 PVID Egress Untaggedeth1 1 Egress Untagged
10 PVID Egress Untaggedeth0 1 PVID Egress Untagged
2-99
201-4094Internally all are handled using a (hashed) list of individual VLANs.Note 1
Cumulus Networks (known to mostly use Linux' native network stack on their network equipments) has some old (and newer) examples about this:Consider the following example bridge:
auto bridge
iface bridge
bridge-vlan-aware yes
bridge-ports swp1 swp9
bridge-vids 2-100
bridge-pvid 101
bridge-stp onHere is the VLAN membership for that configuration:
cumulus@switch$ bridge -c vlan show
portvlan ids
swp1 101 PVID Egress Untagged
2-100swp9 101 PVID Egress Untagged
2-100bridge 101The configuration file used is the interfaces file from ifupdown2 (and its addons), actually developed by Cumulus Networks to replace ifupdown, with a mostly compatible syntax, but much improved bridge and VLAN support.Note 2
I didn't find any evidence of some special flag automatically flooding all VLANs to a bridge port. This kernel commit tells VID 4095 is documented in IEEE 802.1Q to have restrictions but allowed to be used for management operations as a wildcard match for the VID, but Linux doesn't seem to use such method.
|
I have an ethernet port attached to a bridge:
$ brctl show
bridge name bridge id STP enabled interfaces
eth0_bridge 8000.6a612bcc4723 yes eth0The bridge is VLAN-aware (ie /sys/class/net/eth0_bridge/bridge/vlan_filtering is 1). I want to be able to add other interfaces to that bridge and assign VLANs to them, like this:
ip link set eth1 master eth0_bridge
bridge vlan add dev eth1 vid 10 pvid untaggedThis should connect untagged traffic on eth1 to VLAN 10 on eth0. But no traffic gets through until I:
bridge vlan add dev eth0 vid 10Once I've done this, then everything works as needed. But is there no way to tell it that eth0 is a trunk port on bridge eth0_bridge that should carry all VLANs and then do the VLAN filtering on egress from the bridge?
| Linux VLAN-aware bridges and trunk ports |
I don't know if Linux supports Cisco's concept of "private VLANs" per se, but what private VLANs essentially are is a link-layer firewall controlling which switch ports can talk to which other switch ports. So if you've got a Linux box with several Ethernet devices and are bridging between them (e.g. with the brctl tool), I think the tool you want is called ebtables. If you're familiar with iptables, it
shouldn't be too hard to pick up from the man page.
Note, though, that describing all of the private VLAN concepts at once using ebtables might be complicated. And if you want to share PVLAN groupings with a Cisco switch (assuming that's possible), I'm guessing this isn't the way to go about it.
|
Has anyone tried private VLANs under Linux? Any experiences with them? My real question is does anybody have howtos regarding this?
| Private VLAN's under Linux? |
You need to configure the devices, then the bond and finally the VLAN config files. You also have to pay attention on what attributes work where, such as the bonding_opts, which can only be in the bond its self, not the VLAN config files as the VLAN files won't be able to access the Ethernet connections directly.
I have also found this RHEL 6 document that explains it more. It's also still mostly reliable for RHEL 7 / CentOS 7.CONFIGURING A VLAN OVER A BONDAdded:
The bond is responsible for the management of the physical connections the bond uses. the VLANs have no visibility into the physical connections as shown from the driver output below; they only see the device responsible for them, in this case, bond0.
Also explained here for another point of view:
bonded-and-primary-virtual-ip-addresses-and-vlan-tagged Answer
Notes:I know this works as I have it working on a RHEL 7 system.
If you need more VLAN's, just cp ifcfg-bond0.20 ifcfg-bond0.30 and update the required fields.Diagram:
eth0 vlan1
\ /
bond0 -vlan2
/ \
eth1 vlan3Example:
[Working config]
==> ifcfg-eth0 <==
DEVICE=eth0
NAME=bond0-slave
HWADDR=xx:xx:xx:xx:xx:xx
ONBOOT=yes
BOOTPROTO=none
MASTER=bond0
SLAVE=yes
USERCTL=no
NM_CONTRLLED=no ==> ifcfg-eth1 <==
DEVICE=eth1
NAME=bond0-slave
HWADDR=xx:xx:xx:xx:xx:xx
ONBOOT=yes
BOOTPROTO=none
MASTER=bond0
SLAVE=yes
USERCTL=no
NM_CONTRLLED=no ==> ifcfg-bond0 <==
DEVICE=bond0
TYPE=bond
BONDING_MASTER=yes
NAME=bond0
ONBOOT=yes
BONDING_OPTS="miimon=100 mode=active-backup" ==> ifcfg-bond0.10 <==
VLAN=yes
TYPE=vlan
DEVICE=bond0.10
PHYSDEV=bond0
VLAN_ID=10
BOOTPROTO=none
NAME=bond0.10
ONBOOT=yes
IPADDR=x.x.x.x
PREFIX=24
GATEWAY=x.x.x.1
IPV6INIT=no
DEFROUTE=yes ==> ifcfg-bond0.20 <==
VLAN=yes
TYPE=vlan
DEVICE=bond0.20
PHYSDEV=bond0
VLAN_ID=20
BOOTPROTO=none
NAME=bond0.20
ONBOOT=yes
IPADDR=x.x.x.x
PREFIX=24
GATEWAY=x.x.x.1
IPV6INIT=no
DEFROUTE=nodrivers in use:
[thebtm@server network-scripts]$ sudo cat /proc/net/bonding/bond0
Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011) Bonding Mode: fault-tolerance (active-backup)
Primary Slave: None
Currently Active Slave: eth0
MII Status: up
MII Polling Interval (ms): 100
Up Delay (ms): 0
Down Delay (ms): 0 Slave Interface: eth0
MII Status: up
Speed: 10000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: xx:xx:xx:xx:xx:xx
Slave queue ID: 0 Slave Interface: eth1
MII Status: up
Speed: 10000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: xx:xx:xx:xx:xx:xx
Slave queue ID: 0[thebtm@server network-scripts]$ sudo cat /proc/net/vlan/bond0.10
bond0.10 VID: 10 REORDER_HDR: 1 dev->priv_flags: 1
total frames received 29091167441
total bytes received 139953896100912
Broadcast/Multicast Rcvd 18 total frames transmitted 21506143557
total bytes transmitted 14822425401382
Device: bond0
INGRESS priority mappings: 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0
EGRESS priority mappings:
[thebtm@server network-scripts]$ sudo cat /proc/net/vlan/bond0.20
bond0.20 VID: 20 REORDER_HDR: 1 dev->priv_flags: 1
total frames received 2637498
total bytes received 290061293
Broadcast/Multicast Rcvd 5 total frames transmitted 6
total bytes transmitted 252
Device: bond0
INGRESS priority mappings: 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0
EGRESS priority mappings: |
Do you think following configuration make sense? Does BONDTING_OPT supported in VLAN interface? I want to make sure my interface fails over when the upstream device down.
ifcfg-bond0
$ cat /etc/sysconfig/network-scripts/ifcfg-bond0
NAME=bond0
DEVICE=bond0
BOOTPROTO=none
ONBOOT=yes
BONDING_OPTS="mode=1 miimon=500 downdelay=1000 primary=eno1 primary_reselect=always"ifcfg-bond0.10
$ cat /etc/sysconfig/network-scripts/ifcfg-bond0.10
NAME=bond0.10
DEVICE=bond0.10
ONPARENT=yes
BOOTPROTO=dhcp
VLAN=yes
BONDING_OPTS="mode=1 arp_interval=1000 arp_ip_target=10.10.0.1 miimon=500 downdelay=1000 primary=eno1 primary_reselect=always"
NM_CONTROLLED=noifcfg-bond0.20
$ cat /etc/sysconfig/network-scripts/ifcfg-bond0.20
NAME=bond0.20
DEVICE=bond0.20
ONPARENT=yes
BOOTPROTO=dhcp
VLAN=yes
BONDING_OPTS="mode=1 arp_interval=1000 arp_ip_target=74.xx.xx.1 miimon=500 downdelay=1000 primary=eno1 primary_reselect=always"
NM_CONTROLLED=no | Linux bond with VLAN question |
In your particular example, br0 is consuming the packets from eth0 and the VLAN code is not getting them. That's probably the right behaviour.
If you are adding a trunk port to a bridge, you should run the VLANs off the bridge:
brctl addbr br0
brctl addif br0 eth0
ip link set br0 upvconfig add br0 2
brctl addbr br2
brctl addif br2 br0.2
ip link set br2 upvconfig add br0 3
brctl addbr br3
brctl addif br3 br0.3
ip link set br3 upI don't have my bridge & vlan setup handy, so I can't test this, but it makes logical sense to me. It removes the conflict between whether VLAN or bridge consumes packets from eth0 and makes the layering clear.
|
I'm working with VLANs on briges and have found that if I add a non-VLAN interface to any bridge, it breaks all the VLAN interfaces - packets leave just fine, but the return packets (which are appropriately VLAN tagged) are getting dropped somewhere. The minute I drop the non-VLAN interface from the bridge, the VLAN interfaces start working again.
What is the reason for this? Is it a bug?
To clear up any possible questions:
#setup bridges and vlans
vconfig add eth0 2
vconfig add eth0 3
brctl addbr br2
brctl addbr br3
brctl addif br2 eth2.2
brctl addif br3 eth2.3
ip link set dev br2 up
ip link set dev br3 up#wait for forwarding state and test
arping -I br2 10.10.10.1
#this works - I get replies
arping -I br3 192.168.1.1
#this works - I get repliesbrctl addbr br0
brctl addif eth0arping -I br2 10.10.10.1
#broken - no replies. Wireshark shows reply packets coming in exactly as before.
arping -I br3 192.168.1.1
#also brokenip link set br0 up
#wait for forwarding mode, then...
arping -I br3 192.168.1.1
#still brokenbrctl delif br0 eth0
arping -I br3 192.168.1.1
#working again! | Why does adding a non-VLANed interface to a bridge break the VLANed interfaces? |
I was able to achieve this with the following nftables ruleset (I had to build nft from source as v0.5 which ships with Ubuntu 16.04 doesn't support packet field mangling) :
table ip mytable {
chain prerouting {
type filter hook prerouting priority -300; policy accept;
iifname "eno2.11" ip saddr 192.168.0.222 ip saddr set 192.168.101.222
iifname "eno2.12" ip saddr 192.168.0.222 ip saddr set 192.168.102.222
iifname "eno2.13" ip saddr 192.168.0.222 ip saddr set 192.168.103.222
} chain output {
type filter hook output priority -300; policy accept;
ip daddr 192.168.101.222 ip daddr set 192.168.0.222
ip daddr 192.168.102.222 ip daddr set 192.168.0.222
ip daddr 192.168.103.222 ip daddr set 192.168.0.222
}
}and the following entries in /etc/network/interfaces:
auto eno2 # For switch management interface
iface eno2 inet static
address 192.168.2.2/24auto eno2.11
iface eno2.11 inet static
address 192.168.101.1
netmask 255.255.255.0auto eno2.12
iface eno2.12 inet static
address 192.168.102.1
netmask 255.255.255.0auto eno2.13
iface eno2.13 inet static
address 192.168.103.1
netmask 255.255.255.0This doesn't "unmangle" the source IP of outgoing packets, i.e. the gadgets still see requests from the server as coming from 192.168.101.1, 192.168.102.1 etc rather than 192.168.0.1 - in my application this doesn't matter but it could probably be addressed with additional rules in the output chain.
|
I have a physical network with a Linux server (Ubuntu 16.04, kernel 4.13) and several gadgets on it. Each gadget has the same unchangeable static IP, e.g. 192.168.0.222/24. I would like to communicate with all these gadgets via an arbitrary IP protocol (e.g. ICMP ping or a custom UDP protocol)
Fortunately I have a managed network switch connecting the server and the gadgets. I've configured the switch to have a trunk port for the server and access ports for each gadget, each on a different VLAN (VIDs 11, 12, etc).
I have added 8021q to /etc/modules and set up VLAN entries in /etc/network/interfaces:
auto eno2 # For switch management interface
iface eno2 inet static
address 192.168.2.2/24auto eno2.11 # Gadget 1 (only)
iface eno2 inet static
address 192.168.0.1/24#auto eno2.12 # Gadget 2 - disabled
#iface eno2 inet static
# address 192.168.0.1/24With the entries as shown above, I can communicate with gadget 1 (e.g. ping 192.168.0.222) and don't see any traffic from gadget 2.
But I'd like to be able to communicate with all gadgets at the same time, and be able to distinguish one from the other. They don't need to talk to each other. I was thinking for each gadget I could create a unique host IP and subnet, e.g.
Host IP & subnet "Fake" gadget IP Actual gadget IP VLAN Interface
192.168.101.1/24 192.168.101.222 192.168.0.222 eno2.11
192.168.102.1/24 192.168.102.222 192.168.0.222 eno2.12I'd use iptables or nftables to handle the translation in each direction. Then I could ping 192.168.101.222 to reach gadget 1, and ping 192.168.102.222 to reach gadget 2. From each gadget's point of view, its own IP would still be 192.168.0.222 and it would see the ICMP echo requests coming from 192.168.0.1.
This seems like a somewhat unusual variant on NAT. Note the traffic with the "fake" IPs doesn't need to (and shouldn't) leave the server - we're not forwarding to something else on the network.Is this a reasonable approach to the problem?
How do I set up /etc/network/interfaces and iptables or nftables to achieve this? | nftables / iptables rules to rewrite source IP by interface |
When you add a VLAN to a device that is already a virtual VLAN interface you get a QinQ interface, this means that packets will eggress with dual VLAN taggs, or VLAN stacking.This is technically possible because a VLAN packet can transport another VLAN packet inside.
|
When configuring an application that creates vlans by using vconfig add, I discovered that it was adding a vlan device to something that was already a vlan device. Effectively, what happened was:
# vconfig add bond0 168
...
# vconfig add bond0.168 100 The vlan100 interface was then attached to a bridge which connects to a KVM instance:
# brctl addbr br100
...
# brctl addif br100 vlan100Here's what the bridges look like:
# brctl show
bridge name bridge id STP enabled interfaces
br100 8000.02163e4fc8db no vlan100
vnet0
virbr0 8000.000000000000 yes Oddly enough, everything seemed to work, I was able to ssh to my KVM instance.
What happens when you add a vlan-device to an interface that is already a vlan device? In particular, what VLAN tag do the ethernet frames have that go to the VM instance?
| What happens if you add a vlan-device to an interface that already is a vlan device? |
I found the command for altering the bridge vlans needs slightly different syntax. 'self' must be appended to the device:
bridge vlan add dev br0 self vid 2 pvidThen the command works as expected.
|
I'm using DSA in Linux to support an ethernet switch (KSZ9897). The switch is behaving but I'm having trouble setting up the bridge vlan filtering features through Linux (kernel 4.19).
I create the bridge and add the member ports like this:
ip link add name br0 type bridge
ip link set dev lanB master br0
ip link set dev lanA master br0At this point, Linux creates the br0 interface and I can ping through this interface to a PC connected to the 'lanB' interface.
Now I want to separate lanA and lanB using VLANs.
Enable vlan filtering, and set up PVIDs:
ip link set dev br0 type bridge vlan_filtering 1
bridge vlan add dev lanB vid 2 pvid untagged master
bridge vlan add dev lanA vid 3 pvid untagged masterWith VLANs setup, I can dump bridge vlan state:
bridge vlan show
port vlan ids
lanB 2 PVID Egress UntaggedlanA 3 PVID Egress Untaggedbr0 1 PVID Egress UntaggedHere we come to the problem. Now I need to set the br0 interface as 2 PVID so that I can ping between the CPU and LANB. But I receive an error:
bridge vlan add dev br0 vid 2 pvid
RTNETLINK answers: Operation not supportedIf I can't change the pvid of the CPU port I'm not sure how to accomplish this. My end goal was to use ip link add link br0 name br0.2 type vlan id 2 to add a vlan interface in order to communicate with lanB. But without configuring the br0 switch port to be part of VLAN 2 this will fail.
Am I approaching this wrong or missing something?
| Linux IP bridge and vlan_filtering |
This is a limitation of current bridge filtering with ebtables: ebtables matches are specific rather than generic, and unless one adds a vlan-plus-ip match, it's not possible to match a VLAN tagged IP with ebtables.
Here are two methods to work around this limitation, while the first method would allow many things for other cases, the specific OP's issue cannot be dealt with it.
bridge-netfilter (cannot work for this case)
What is instead possible for many cases (but actually not this case, see later) related to ebtables' poor handling of stacked protocols , is to tell the bridge code to do an upcall to iptables by using the br_netfilter module. Yes that's right, iptables will be run at the bridge level rather than the route/IP level. Note that currently this is a systemwide change with possible systemwide effects, including on other bridges and other namespaces (this should become per-namespace "soon", probably after kernel 5.3). Some unexpected effects and how to prevent them are described in 7. Two possible ways for frames/packets to pass through the iptables PREROUTING, FORWARD and POSTROUTING chains.
modprobe br_netfilter
sysctl -w net.bridge.bridge-nf-call-iptables=1 #actually defaultNote that there's no action needed on the VLAN part:Do {ip,ip6,arp}tables see VLAN tagged IPv4/IPv6/ARP traffic on an
untagged bridge?
Yes. Kernel versions 2.6.0-test7 and above have this functionality. For disabling this, see the above question.Now that ebtables/iptables interactions are possible, let's look at 5. Chain traversal for bridged IP packets. It tells the frame/packet will at least do:
-> ebtables nat/PREROUTING -> iptables nat/PREROUTING, then
-> ebtables filter/FORWARD -> iptables filter/FORWARD ....There are other cases, but one case that would be needed doesn't exist: come back to the same calling part, like:
-> ebtables nat/PREROUTING -> iptables some/THING -> ebtables nat/PREROUTINGSo while depending on OP's specific layout (including the role of the interface in 2nd rule and the meaning of the MAC address, is it local? not local? etc.) there could be some options left (really needing to mark the packet to send a message from ebtables to iptables), I don't see a way.
That's why an ebtables/iptables replacement was devised that would avoid all this mess in the first place: nftables.
nftables
The replacement nftables was designed with a generic usage in mind, so it wouldn't have to rely on a slightly different kernel module to do the same when handling an IP in bridge path or in route path.
nftables is a moving target, it's probably best to use nftables >= 0.8.3 and kernel >= 4.10 to get most features. This was tested with nftables 0.9.0 and kernel 5.1.x. Old nftables/kernels (eg RHEL7/CentOS7's) might not have all the required features, this has to be tested again then.
There are still some limitations for this specific case, but they appear to be on the userland nftables side rather than the kernel side, so I provide two ways to overcome it.
Let's add the plumbing (eg after a nft flush ruleset):
nft add table bridge nat
nft add chain bridge nat prerouting '{ type filter hook prerouting priority -300; policy accept; }'If the matching IP is 192.0.2.1 and the target MAC is 02:00:00:00:00:01, normally this one line would be enough to do the work (depending on nftables' version it has to be more or less verbosely described,I chose to be verbose, anyway it's creating the exact same bytecode and displayed back in a simplified version), but it fails:
# nft add rule bridge nat prerouting ether type vlan vlan id 100 vlan type ip ip daddr 192.0.2.1 ether daddr set 02:00:00:00:00:01
Error: conflicting protocols specified: vlan vs. ether
add rule bridge nat prerouting ether type vlan vlan id 100 vlan type ip ip daddr 192.0.2.1 ether daddr set 02:00:00:00:00:01
^^^^^^^^^^^The nftables userland tool doesn't want to come back in its parsing to a lower level protocol after having followed ether -> vlan -> ip.
This can be solved either by splitting the rule with a user chain and put the change there:
nft add chain bridge nat mydnat
nft add rule bridge nat prerouting ether type vlan vlan id 100 vlan type ip ip daddr 192.0.2.1 jump mydnat
nft add rule bridge nat mydnat ether daddr set 02:00:00:00:00:01or by telling nftables "do this, don't try to understand" with a raw payload telling to change the first 48 bits of the link layer (that is the ethernet destination MAC). So instead of the 3 lines above, this line will do the same:
nft add rule bridge nat prerouting ether type vlan vlan id 100 vlan type ip ip daddr 192.0.2.1 @ll,0,48 set 0x020000000001Note that the latter method is actually using the same bytecode, doing this instead of the 3rd line of the latter method:
nft add rule bridge nat mydnat @ll,0,48 set 0x020000000001would be decoded back to exactly the same ether daddr set 02:00:00:00:00:01 when displaying the rule in chain mydnat. One can imagine a future version of nftables will accept it in the one liner case.
Just to tell it's working as written (ie: probably not working as intended without additional rules for ARP or context from OP etc.), here's a tcpdump on the receiving side when receiving a ping on 192.0.2.1:
14:03:06.542085 9e:72:8c:20:15:2a > ff:ff:ff:ff:ff:ff, ethertype 802.1Q (0x8100), length 46: vlan 100, p 0, ethertype ARP, Request who-has 192.0.2.1 tell 192.0.2.2, length 28
14:03:06.542135 ae:3a:24:06:a7:da > 9e:72:8c:20:15:2a, ethertype 802.1Q (0x8100), length 46: vlan 100, p 0, ethertype ARP, Reply 192.0.2.1 is-at ae:3a:24:06:a7:da, length 28
14:03:06.542184 9e:72:8c:20:15:2a > 02:00:00:00:00:01, ethertype 802.1Q (0x8100), length 102: vlan 100, p 0, ethertype IPv4, 192.0.2.2 > 192.0.2.1: ICMP echo request, id 21702, seq 1, length 64with its other IP 192.0.2.11 unaffected:
14:11:04.026480 9e:72:8c:20:15:2a > ff:ff:ff:ff:ff:ff, ethertype 802.1Q (0x8100), length 46: vlan 100, p 0, ethertype ARP, Request who-has 192.0.2.11 tell 192.0.2.2, length 28
14:11:04.026491 ae:3a:24:06:a7:da > 9e:72:8c:20:15:2a, ethertype 802.1Q (0x8100), length 46: vlan 100, p 0, ethertype ARP, Reply 192.0.2.11 is-at ae:3a:24:06:a7:da, length 28
14:11:04.026505 9e:72:8c:20:15:2a > ae:3a:24:06:a7:da, ethertype 802.1Q (0x8100), length 102: vlan 100, p 0, ethertype IPv4, 192.0.2.2 > 192.0.2.11: ICMP echo request, id 21895, seq 1, length 64
14:11:04.026515 ae:3a:24:06:a7:da > 9e:72:8c:20:15:2a, ethertype 802.1Q (0x8100), length 102: vlan 100, p 0, ethertype IPv4, 192.0.2.11 > 192.0.2.2: ICMP echo reply, id 21895, seq 1, length 64 |
ebtable rule is not allowing me to specify vlanid and ipv4 protocol in one rule. Also I tried this but the second rule is not getting matched for vlan packet.
ebtables -t nat -A PREROUTING --vlan-id 100 -j mark --set-mark 100 --mark-target CONTINUE
ebtables -t nat -A PREROUTING -i <iface> --mark 100 --ip-dst <ip> -j dnat --to-dst <mac> --dnat-target ACCEPTThe second rule is not getting matched if packet comes with vlan header. Is there any way I can do DNAT mac based on matching destination ipaddress and vlan id?
| Need to DNAT mac based on vlan and destination IP match. |
There is only one physical interface: eth0. Any virtual interface (here: eth0.0001) linked to the actual interface is showing encapsulated traffic in its virtual view until the traffic is emitted through the actual interface.
The network stack will make such traffic move through each interface until it reaches the final interface where it leaves the machine. Each step can be captured separately, leading to multiple captures of the same payload, but with different encapsulation properties.
So here what happens (in a very simplified view) as visible with Wireshark:the VLAN interface is showing the payload withing the VLAN frame, so doesn't show any VLAN
This virtual interface is the one participating in routing with regard to IP LAN 192.168.1.0/24. An IP packet is emitted, and is itself encapsulated inside a (normal) Ethernet frame. (Before this could be done ARP traffic would also have happened, but is not in the capture). This frame is captured by Wireshark before being given to the network part handling VLAN interfaces.the eth0 interface is showing the encapsulated payload, so shows VLAN ID 1.
The previous Ethernet frame in eth0.0001 gets encapsulated with an additional VLAN tag (adding 4 bytes to the frame) once reaching eth0 and is captured, again but not the same, by Wireshark before being given to the actual NIC's hardware by the NIC's driver.Wireshark (nor tcpdump for this very simple case) doesn't stop at the first layer but displays more: IPv4 decoding with addresses and IP protocol (ICMP).
|
I have a problem with VLAN tagging. I am completely newbie about VLAN so maybe there is something I misunderstood at all...
Basically: I have a Linux box configured via /etc/network/interfaces as:
allow-hotplug eth0
iface eth0 inet static
address 192.168.70.31
netmask 255.255.255.0allow-hotplug eth0.0001
iface eth0.0001 inet static
address 192.168.1.31
netmask 255.255.255.0I adjusted the routing table so that now I have (output of ip r command):
192.168.1.0/24 dev eth0.0001 proto kernel scope link src 192.168.1.31
192.168.70.0/24 dev eth0 proto kernel scope link src 192.168.70.31If I monitor packets with Wireshark while pinging another host tagged with VLAN ID 1 (192.168.1.30 in my test) then I see that my host emits duplicated packets, one with the proper VLAN ID and another one (coming out from the same 192.168.1.31 interface!) without the VLAN tag. The other host responds to both packets, respectively with and without the proper VLAN tag, as you can see in the screenshot here below:The question is: why is my host emitting duplicated packets? If pinging another host in 192.168.1.x network, shouldn't it only emit one packet with the proper VLAN tag (1 in my case)?
| VLAN tagging: duplicated packets |
You can configure the port to use a specific Port VLAN ID (pvid) for all received untagged frames and configure this same VLAN ID to be emitted as untagged frames (untagged). While it's possible to emit multiple VLANs as untagged, there's no real use, because the other VLANs that are not the PVID on this port will never see traffic replies in this case, since any possible untagged reply traffic goes only to the PVID: for a given bridge port, both flags are usually present for one VLAN ID only. Simply choose any random VLAN ID (it will never be seen on the wire), for example 42:
bridge vlan add vid 42 dev wlan2.2 pvid untaggedand configure any other port that should communicate with it in the same manner, PVID+untagged as above or tagged as needed (if tagged VLAN ID 42 will then be seen on this wire).
The last part does matter: without any other port (including the bridge interface) knowing about VLAN 42 frames will just be dropped. For example with a newly added bridge port foo0:
bridge vlan delete vid 1 dev foo0
bridge vlan add vid 42 dev foo0 pvid untaggedand the other tagged VLANs too:
bridge vlan add vid 10 dev foo0
bridge vlan add vid 20 dev foo0Actually if you never deleted this default VLAN ID 1 as done above, then the behavior is already as you described using VLAN ID 1: all ports default to PVID 1 untagged. So if the bridge (that I'll name bridge0) and the port wlan2.2 were configured as you wrote, where VLAN ID 1 was never deleted then there's nothing to do to get this behavior. Here's a mockup:
ip link add name bridge0 up type bridge vlan_filtering 1
ip link add wlan2.2 up master bridge0 type dummy
bridge vlan add vid 10 dev wlan2.2
bridge vlan add vid 20 dev wlan2.2# bridge vlan show
port vlan-id
bridge0 1 PVID Egress Untagged
wlan2.2 1 PVID Egress Untagged
10
20All interfaces/ports already have PVID 1 untagged by default, thus working as intended without any change, including without the change I wrote above.About the bridge itself and routing
Note that the bridge interface behaves slightly differently from the bridge ports since it participates in routing. Changing VLAN IDs for the bridge interface itself also requires the keyword self (this usage of self appears to lack unambiguous documentation in man page) in addition to other settings, and this will also affect routing connectivity of the bridge interface. Routing requires untagged frames, so only one VLAN is available for proper routing directly with the bridge interface (more could be made available either by using classic VLAN interfaces on top of the bridge interface, or else with veth interfaces with one side set as bridge port and the other side with an IP address). Like other ports, it's also defaulting to PVID 1 untagged as seen above. You can choose to switch it to VLAN 42 to route the untagged traffic received on port wlan2.2 (and lose any former traffic/connectivity from default VLAN 1 that could come from elsewhere):
bridge vlan delete vid 1 dev bridge0 self
bridge vlan add vid 42 dev bridge0 pvid untagged self |
I'm using VLAN aware bridge.
I have an interface that I need that only packets with VID 10 and 20 could pass through, any other VIDs should be dropped.
I configured the interface like that:
bridge vlan add vid 10 dev wlan2.2
bridge vlan add vid 20 dev wlan2.2My problem is that I want to allow untagged traffic to also pass through, without modifying/adding tag to the packet.
Can it be done?
| How to allow VLAN untagged packet to pass through when using VLAN aware bridge |
If I understand correctly you have this arrangement:
(Client)---LAN?---(VPN)---ppp0---(Raspberry Pi)---wlan0---(the internet)You mentioned that when you change your default route to use wlan0, you lose SSH access. You also indicated that you can't access the internet through ppp0 (through your VPN).If you just want your r-pi to have internet access...
You can't SSH into your PI when you change the default route because the default route is the only one that can get to your SSH client. So what you can do is add a new route to talk back to your SSH client then change your default route.
A really simple / dirty way to fix this temporarily is:
# Find your current SSH client IP address as seen by the raspberry pi
env | grep SSH_CLIENTThen assuming this gives you the IP 10.20.30.40 add a route to just that IP:
ip route add 10.20.30.40 dev ppp0 proto kernel scope link
# Now you can change your default route
ip route change default via 192.168.1.1 dev wlan0A better way to do this is to discover which subnet(s) can be accessed through ppp0 and then create routes for those instead of just your one SSH client. I can't tell how to find these subnets. But once you have this, the technique is the same. (eg subnet 10.20.0.0/16):
ip route add 10.20.0.0/16 dev ppp0 proto kernel scope link
# Now you can change your default route
ip route change default via 192.168.1.1 dev wlan0 |
I need to install remotely Omxplayer on a Raspberry Pi.
RPi is connected by a LTE modem through PPP0 interface.
My RPI is placed another country and I connect to Raspberry through my VPN using SSH.
My VPN does not have access to Internet and the default gateway is 10.1.64.1 (PPP0).
RPI has also WiFi Connection: WLAN0 interface.
I want to use WLAN0 to launch:"sudo apt-get install omxplayer" without lost my SSH communication through PPP0
ifconfig
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 184 bytes 11776 (11.5 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 184 bytes 11776 (11.5 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0ppp0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> mtu 1500
inet 10.1.64.45 netmask 255.255.255.255 destination 10.64.64.64
ppp txqueuelen 3 (Point-to-Point Protocol)
RX packets 202 bytes 25021 (24.4 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 808 bytes 65151 (63.6 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.1.93 netmask 255.255.255.0 broadcast 192.168.1.255
inet6 fe80::2db7:3540:5e17:a470 prefixlen 64 scopeid 0x20<link>
ether b8:27:eb:da:d6:37 txqueuelen 1000 (Ethernet)
RX packets 1806 bytes 369775 (361.1 KiB)
RX errors 0 dropped 620 overruns 0 frame 0
TX packets 184 bytes 25229 (24.6 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0If I change the default gateway, I lost connectivity with the device.
I have tried the following command but it has not worked: I have lost the ssh connection.
sudo ip route change default via 192.168.1.1 dev wlan0sudo route add default gw 192.168.1.1My route table:
$ route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 0.0.0.0 0.0.0.0 U 0 0 0 ppp0
0.0.0.0 192.168.1.1 0.0.0.0 UG 302 0 0 wlan0
10.64.64.64 0.0.0.0 255.255.255.255 UH 0 0 0 ppp0
169.254.0.0 0.0.0.0 255.255.0.0 U 203 0 0 wwan0
192.168.1.0 0.0.0.0 255.255.255.0 U 302 0 0 wlan0$ ip route show
default dev ppp0 scope link
default via 192.168.1.1 dev wlan0 src 192.168.1.205 metric 302
10.64.64.64 dev ppp0 proto kernel scope link src 10.1.64.54
169.254.0.0/16 dev wwan0 proto kernel scope link src 169.254.104.103 metric 203
192.168.1.0/24 dev wlan0 proto kernel scope link src 192.168.1.205 metric 302How can I select the network interface?
Thanks in advance
| How can I select the network interface for installing a program in linux? |
The answer is: Yes it is possible. At least with RedHat, where the bonding of virtual interfaces works the same way as the bonding of physical interfaces.
It is even possible to bond (mode=broadcast) virtual interfaces which are configured for different Vlan-IDs. The result is that the packages sent to the bonding interface appear on all bonded Vlans each with the correct Vlan-ID.
Note that this is not officially supported by RedHat6. It not known to me whether it is officially supported in RedHat7.
|
Is it possible to bond virtual network interfaces? If yes, how?
Bonding of physical interfaces is explained here for example: https://wiki.linuxfoundation.org/networking/bonding
My situation is this:
I have a host with 10 physical ethernet interfaces (NICs). Each of those is a trunk for multiple VLANs. I plan to make a virtual ethernet interface on each physical interface for each VLAN. Example: eth0 carries 3 VLANs (3,11,15) -> I create eth0.0 (VLAN3), eth0.1(VLAN11) and eth0.2(VLAN15).
I further want to include some redundancy. I think of the bonding mode "active backup". The idea was to bond multiple virtual interfaces, which belong to different physical interfaces, e.g. eth0.5, eth2.3 and eth8.4. Since this is a bigger project I wanted to make sure this works beforehand. If this works in general, do the bonded virtual interfaces have to have the same VLAN ID, i.e. would it work if (in the example above) eth0.5 had VLAN 22, eth2.3 VLAN 42 and eth8.4 VLAN 52?
| Bonding of virtual network interfaces |
Manually: ifconfig $DEVICE 0.0.0.0 up should remove the IP and leave the interface up and running.
Some distributions allow such a configuration statically, others do not.
Perhaps you can set up a bridge-device instead.
|
On Arch Linux, I have a single physical ethernet interface on 2 VLANs (3 and 7) with static IP addresses for the VLANs and a DHCP address for the 'main' ethernet interface.
Is there a way for me to remove the IP address from eth0 and just have the VLANs? Or is there a way to assign eth0 to a VLAN? I'd prefer this to be done as part of the /etc/netctl or /etc/systemd/network configuration files.
The result of ip addr is:1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 6c:ec:eb:5c:a3:0b brd ff:ff:ff:ff:ff:ff
inet 192.168.106.55/24 brd 192.168.106.255 scope global eth0
inet6 fe80::6eec:ebff:fe5c:a30b/64 scope link
valid_lft forever preferred_lft forever
3: eth0.7@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 6c:ec:eb:5c:a3:0b brd ff:ff:ff:ff:ff:ff
inet 10.0.0.1/24 brd 10.0.0.255 scope global eth0.7
inet6 fe80::6eec:ebff:fe5c:a30b/64 scope link
valid_lft forever preferred_lft forever
4: eth0.3@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 6c:ec:eb:5c:a3:0b brd ff:ff:ff:ff:ff:ff
inet 192.168.1.7/24 brd 192.168.1.255 scope global eth0.3
inet6 fe80::6eec:ebff:fe5c:a30b/64 scope link
valid_lft forever preferred_lft forever
And the result of ip -d link is:1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 promiscuity 0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
link/ether 6c:ec:eb:5c:a3:0b brd ff:ff:ff:ff:ff:ff promiscuity 0
3: eth0.3@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default
link/ether 6c:ec:eb:5c:a3:0b brd ff:ff:ff:ff:ff:ff promiscuity 0
vlan protocol 802.1q id 3 <REORDER_HDR>
4: eth0.7@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default
link/ether 6c:ec:eb:5c:a3:0b brd ff:ff:ff:ff:ff:ff promiscuity 0
vlan protocol 802.1q id 7 <REORDER_HDR>
| Remove IP address from interface with VLANs |
The source issue was a simple sequencing problem regarding the vlan interface.
My network interface persistence file was initially misconfigured:
# WAN vlan 832 internet
auto enp1s0.832
iface enp1s0.832 inet dhcp
up ip link set enp1s0.832 type vlan egress 0:0 1:0 2:0 3:0 4:0 5:0 6:6 7:0
iface enp1s0.832 inet6 dhcp
up ip link set enp1s0.832 type vlan egress 0:0 1:0 2:0 3:0 4:0 5:0 6:6 7:0
request_prefix 1
accept_ra 2The bad part it the "up" instruction. The egress mapping is done too late, when initial ARP / DHCP / NDP has already happened.
The fix is really simple, it suffices to use pre-up instead:
# WAN vlan 832 internet
auto enp1s0.832
iface enp1s0.832 inet dhcp
pre-up ip link set enp1s0.832 type vlan egress 0:0 1:0 2:0 3:0 4:0 5:0 6:6 7:0
iface enp1s0.832 inet6 dhcp
pre-up ip link set enp1s0.832 type vlan egress 0:0 1:0 2:0 3:0 4:0 5:0 6:6 7:0
request_prefix 1
accept_ra 2With that, the initial ARP/DHCP/NDP handshake is done with right QoS priority.
|
My linux home router sits between my ISP (Orange) and my home network.
On the WAN side, Orange provide internet in a VLAN tagged 832.
Some control messages (ARP, DHCP, ICMPv6 "router discovery" types, DHCPv6) need to be replied to Orange with:
- VLAN priority = 6
- IPv4 or IPv6 DSCP = "CS6" (6 bits 0x30, or 48 in decimal notation)
First problem, for the boot sequence DHCP v4 messages, isc-dhclient needs to use a raw ethernet packet socket, which bypass the linux kernel IP stack by design.
So one cannot use netfilter to assign IPv4 DSCP or Meta Class, but let's leave that aside for now.
Here's a dump of my nftables configuration, relevant to the alteration of IP DSCP and Meta Priority:
me@debox:~$ sudo /usr/sbin/nft list ruleset
table inet fltr46 {
chain assign-orange-prio {
ip version 4 udp sport { bootps, bootpc} ip dscp set cs6 meta priority set 0:6 counter packets 0 bytes 0 comment "isc-dhclient LPF socket bypass netfilter"
icmpv6 type { nd-neighbor-solicit, nd-router-solicit} ip6 dscp set cs6 meta priority set 0:6 counter packets 8 bytes 480
udp sport { dhcpv6-client, dhcpv6-server} ip6 dscp set cs6 meta priority set 0:6 counter packets 4 bytes 1180
} chain postrouting {
type filter hook postrouting priority 0; policy accept;
oifname vmap { "enp1s0.832" : goto assign-orange-prio}
} chain output {
type filter hook output priority 0; policy accept;
oifname vmap { "enp1s0.832" : goto assign-orange-prio }
}
}
table arp arp4 {
chain output {
type filter hook output priority 0; policy accept;
oifname ! "enp1s0.832" accept
meta priority set 0:6 counter packets 851 bytes 35742
}
}My vlan 832 configuration is as follows:
me@debox:~$ sudo cat /proc/net/vlan/enp1s0.832
enp1s0.832 VID: 832 REORDER_HDR: 1 dev->priv_flags: 1001
Device: enp1s0
INGRESS priority mappings: 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0
EGRESS priority mappings: 6:6Which means, for egress, class 6 packets -> VLAN prio 6.
The nftables counters for DHCPv6, ICMPv6 "router", and ARP are incremented, as expected.
However, I notice problems in my wire shark capture (done by swich port mirroring):DHCPv6: OK. DSCP = CS6 and VLAN prio = 6
ICMPv6: not OK. DSCP = CS6 but VLAN prio = 0
ARP: not OK. VLAN prio = 0
IPv4 DHCP lease renewal packets, sent through a regular UDP socket, are also OK (DSCP+VLAN prio).VLAN priority is not applied correctly to ARP and ICMPv6 packets.
Is there a way to debug further why the meta class does not translate correctly to VLAN prio,
for ARP and ICMPv6 messages generated by the linux kernel?
| Packet meta class applied, but captured VLAN priority is wrong |
The Banana R1/Lamobo R1 while an interesting piece of hardware has too many shortcomings.
Firstly, the "switch" internal interface bandwidth is shared. A theoretical 1GBps tops for all shared 5 ports; the official speed people been able to get from it per interface is around 300Mbit.
Second, it has to be setup for that, in the device tree (overlays?) by the OS being used - cannot remember the specific details. Or otherwise it will be slow.
Bananian Linux is an ugly hack, does not work well, it will give you problems, and may not setup well your gigabit switch. Furthermore, Bananian is officially a deprecated project since the end of the 1st quarter of 2017, and security updates for it will stop appearing in a couple of months.
I used the R1 with Armbian for a while; it worked well. I also cut physically the realtek wifi from it, it only created instability even when not being used.
You might also got power issues with mechanical hard disks; I used an SSD.
As a recommendation, stop using Bananian, and try ArmBian. Beware the switch interface is different in Armbian as it uses a more recent kernel 4.x.
Lastly, do not even waste time trying the OpenWRT version for R1. It is a botched job and is full of hacks for working around the big firewall of China.
Leaving now R1 specific considerations, and going to the routing side, one optimisation that can be done in most consumer-grade ISP routers is setting up a port with bridging and connecting your R1 there. Thus, your outside interface will get a public IP address, and your NAT won't have again a double NAT from the ISP. (I am doing the same here)
PS For readers coming here. The R1/R1S is not worth your time and money, get instead an AP router that can be hacked with OpenWRT.
|
I am currently setting up my iot router and ran into some issues regarding connection speed. The router itself is a cascading router. My Internet speed is 100Mbit which I verified by directly connecting to the main router via speed test. However, if I connect it via my cascading router, I only get a connection speed of between 10-18Mbit. I think either Kernel IP forwarding or Iptables NAT is likely misconfigured.
The Operating system is Debian 8 Kernel Version 3.4 (Bananian Linux)
The Router itself is a Banana PI BPI R1
Iptables is running version v1.4.21
The relevant commands I ran to set up my network are
iptables -P FORWARD ACCEPT
iptables -t nat -A POSTROUTING -o eth0.101 -j MASQUERADE(eth0.101 is the output interface that is connected to the main router.)
ip forwarding is enabled via systemctl
ipv6 is completely disabled
since the router’s network card uses an internal switch, I have to use vlans to separate the "lan" from the "wan" I achieve this via the tool swconfig
swconfig dev eth0 set reset 1
swconfig dev eth0 set enable_vlan 1
swconfig dev eth0 vlan 101 set ports '3 8t'
swconfig dev eth0 vlan 102 set ports '4 0 1 2 8t'
swconfig dev eth0 set apply 1
Why do I think this is the NAT/Forwarding?
My first thought was, well my network card is not capable of higher speeds even though it says it is. However to confirm this I ran a socks5 proxy on my router and disabled IP forwarding for the test, when running a speedtest via this socks5 proxy I was able to achieve the 100Mbit which makes me conclude that it is not my network card that is bottlenecking this.
I have tried a few things, including increasing the sizes of packet queues for my VLAN interfaces as they were zero, this changed nothing.
I also do not think that the CPU of my router is too weak to run this, because why would it be strong enough to work with a generic socks5 proxy and too weak to work with iptables?
Here is an output of ifconfig:
eth0 Link encap:Ethernet HWaddr 02:07:0b:02:15:ac
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:370503 errors:0 dropped:0 overruns:0 frame:0
TX packets:365330 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:310436570 (296.0 MiB) TX bytes:308685327 (294.3 MiB)
Interrupt:117 Base address:0xc000eth0.101 Link encap:Ethernet HWaddr 02:07:0b:02:15:ac
inet addr:192.168.178.2 Bcast:192.168.178.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:209032 errors:0 dropped:0 overruns:0 frame:0
TX packets:171418 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:203959632 (194.5 MiB) TX bytes:102579119 (97.8 MiB)eth0.102 Link encap:Ethernet HWaddr 02:07:0b:02:15:ac
inet addr:10.8.0.1 Bcast:10.8.0.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:161471 errors:0 dropped:0 overruns:0 frame:0
TX packets:193912 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:99807884 (95.1 MiB) TX bytes:204644888 (195.1 MiB)lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)as well as /etc/network/interfaces:
auto lo
iface lo inet loopbackauto eth0.101
iface eth0.101 inet static
address 192.168.178.2
network 192.168.178.0
netmask 255.255.255.0
gateway 192.168.178.1
nameserver 8.8.8.8auto eth0.102
iface eth0.102 inet static
address 10.8.0.1
network 10.8.0.0
netmask 255.255.255.0Any ideas would be very much appreciated.
| Iptables NAT / Kernel IP forwarding limited to ~10Mbit |
FreeBSD is not like Linux. This is particularly true regarding network configuration: "everything" is in ifconfig. A simple man ifconfig will confirm you that.
So to change the value of vlanpcp for you re0_vlan2:
ifconfig re0_vlan2 vlanpcp 3More to read:ifconfig manual
vlan mini-HowTo (slightly out-dated) |
This question could arguably be posted on both networking.stackexchange and unix.stackexchange. I'll start here.
I have a freeBSD (pfsense 2.1) server running as a router on google fiber.
In order to get above 10 Mbps I need to enable egress filtering on the wan port
(aka 802.1p, traffic priority, Class of Service, CoS, vlan pcp ).
Running ifconfig, I can see that the vlanpcp is set to 0.
How do I change the vlanpcp from 0 to 3 ?
ifconfig
...
re0_vlan2: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
options=3<RXCSUM,TXCSUM>
ether 00:1c:c0:d5:e0:e2
inet 23.255.241.45 netmask 0xfffff800 broadcast 23.255.247.255
inet6 fe80::21c:c0ff:fed5:e0e2%re0_vlan2 prefixlen 64 scopeid 0x8
nd6 options=3<PERFORMNUD,ACCEPT_RTADV>
media: Ethernet autoselect (1000baseT <full-duplex>)
status: active
vlan: 2 vlanpcp: 0 parent interface: re0It looks link on linux this can be done with vconfig, however freebsd doesn't use vconfig.
For reference, I am using these instructions for setting up the vlans.
https://www.dropbox.com/s/zg9ju9373t0fnpu/GoogleFiberRouterGuide.pdf
https://productforums.google.com/forum/#!topic/fiber/AbNh8ij72Mw
| How do you set a vlan priority on a nic in freeBSD? |
Introduction/Initial setup
This answer doesn't attempt to integrate in network configuration tools the commands used below. The following tools, at least, are expected to be usable for this purpose without requiring extra commands:ifupdown2 (not the original ifupdown)
but there might be a bug for configuring a PVID different than 1 on the bridge's self interface, affecting this case. Thus still leaving...ifupdown-ngsystemd-networkd???A VLAN-aware bridge interface can fix a single VLAN misconfigured like this, by using a Port VLAN ID (PVID). It will be used only as a layer to cancel the external misconfiguration, even if using a single bridge port.
As no initial configuration was provided to build upon, I use an example with VLAN 10 and IP address 192.0.2.2/24 used within this VLAN, with interface eth0. Consider the initial configuration to be like this:
ip link set dev eth0 up
ip link add link eth0 name eth0.10 up type vlan id 10
ip addr add dev eth0.10 192.0.2.2/24 # or use DHCP
ip route add default via 192.0.2.1 dev eth0.10Because of OP's current case, this wouldn't work because the network stack (eg: ARP reply received on eth0 and ignored when expected on eth0.10) or other components (DHCP client using a RAW socket receiving replies on an interface it's not listening on) will ignore return traffic because (due to outside bug) it's not the same interface (untagged eth0, isntead of tagged eth0 <=> untagged eth0.10).
Using a VLAN-aware bridge instead
What can be done is replace the use of a VLAN interface by a VLAN-aware bridge with a single bridge port (eth0). VLAN tagging and Port VLAN ID can now be dynamically configured on the bridge instead of creating/deleting VLAN interfaces. Adequate configuration will cancel the remote misconfiguration.Clean previous state (warning: connectivity loss)
ip link del dev eth0.10Create VLAN-aware bridge
ip link add name br0 type bridge vlan_filtering 1 vlan_default_pvid 0Above vlan_filtering 1 creates the bridge VLAN-aware and vlan_default_pvid 0 makes it use no VLAN by default, so there will be no need to first delete unused VLANs anywhere. VLANs will have to be added explicitly for actual bridge communication to start.Optional: (mainly for MAC-based DHCP server configuration keeping the same address) copy eth0's MAC address to br0
... because this address won't be inherited in any recent systemd environment. With the help of the jq command one can copy eth0's MAC address to br0. This should be done before setting eth0 as bridge port.
ip link set dev br0 address "$(ip -json link show dev eth0 | jq -r '.[].address')"Set eth0 as bridge port and set the bridge up:
ip link set dev eth0 master br0
ip link set br0 upConfigure the bridge interface itself, the only part of the bridge linked to the routing stack, as untagged and PVID 10: the routing stack doesn't handle VLANs frames, only IP (and ARP) frames, so make sure no tagged frames are emitted or expected.
The obsolete brctl command can't handle VLAN-aware bridges. This requires the bridge vlan ... command already provided by the iproute2 suite. When it's about the bridge interface itself rather than a bridge port the additional keyword self is needed.
bridge vlan add vid 10 dev br0 pvid untagged selfAdd the bridge port eth0 as (tagged) VLAN 10 but also as PVID: it will thus emit tagged frames, and will accept both tagged frames (only VLAN 10) and also consider untagged frames as VLAN 10 frames: will work with the switch misconfigured or not.
bridge vlan add vid 10 dev eth0 pvidAlternatively, have the bridge first accept all tagged VLANs first and alter configuration just for VLAN 10. This is useless in the current configuration but would be useful if (an) other bridge port(s) is/are added to bridge traffic elsewhere. That would be:
bridge vlan add vid 2-4094 dev eth0
bridge vlan add vid 10 dev eth0 pvidwhich would get:
# bridge -compressvlans vlan show
port vlan-id
eth0 2-9
10 PVID
11-4094
br0 10 PVID Egress UntaggedThis will now work around the misconfiguration and allow normal use of br0 as the main interface, for example by configuring back a static address on it like this is expected to allow communication:
ip addr add 192.0.2.2/24 dev br0
ip route add default via 192.0.2.1or by running a DHCP client on br0 to configure it.
To change the VLAN to tune in, for example from VLAN 10 to VLAN 11:Reconfigure bridge interface br0
bridge vlan del vid 10 dev br0 self
bridge vlan add vid 11 dev br0 pvid untagged selfReconfigure bridge port eth0
bridge vlan del vid 10 dev eth0
bridge vlan add vid 11 dev eth0 pvidIf instead all VLANs have to be received, since there is only one PVID per port, switch it to VLAN 11 instead without deleting VLAN 10:
bridge vlan add vid 11 dev eth0 pvidNotesThis answer was tested by simulating the misconfigured switch using... a Linux VLAN-aware bridge with the system's side bridge port on VLAN 10 but also untagged.
As there's now a new bridge around, expect issues if the module br_netfilter is loaded: running Docker on this system might require additional workarounds. |
I am trying to implement an obscure workaround to a specific problem tied to a switch misconfiguration I observe in a real case scenario.
Please just assume the following :My system is plugged to a trunk link with a cisco switch ;
I can send tagged packets in a specific VLAN (not native vlan), it will be properly routed to the correct VLAN ;
I receive responses as untagged traffic, even though it is on a trunk and from not-native VLAN ;
I cannot modify the switch's configuration.What I am trying to perform is a way to use a single network interface on Debian, where I can send and receive traffic correctly to insert my traffic in the desired VLAN, even though the packets must be tagged going out and will be caught back untagged.
To give an example, It is possible to ping a remote system with an ICMP echo request. Using my simple eth0 interface will have no effect, no ICMP echo reply will be seen back. However, if I tag my ICMP echo request in say VLAN 10, I will receive an untagged ICMP echo reply ! It works also with DHCP for example (the remote network do has a DHCP server). If I send a tagged DHCP discover packet, I will receive an untagged DHCP offer with the corresponding transaction ID.
I know this is not normal behavior and it can end up in having packets being wrongly routed or assumed to be in a VLAN falsely. It is due to switches being misconfigured (I think it has something to do with native vlan mismatch somewhere).
If I use a vlan subinterface (ip link add link type vlan ...), I will send tagged traffic but responses will never be routed back from the main interface to the sub interface because it expects traffic to be tagged back.
I then discovered vlan aware bridges, which look like a proper solution to my problem, though I dont succeed in doing this with the bridge vlan add commands (pvid, vid, untagged or not, do I need to use a vlan sub-interface anyway ?).
I only need to do this for a single VLAN at a time. It will not be possible to determine to which VLAN a packet is sent because of the tags missing. However, I can infer this VLAN tag based on IP address, STP and CDP traffic. I do not want to do anything automated, I dont want to guess the vlan, I just want to be able to force untagged traffic to be considered being in a chosen, arbitrary vlan, one at a time.
Thank you !
| How to create a linux vlan aware bridge with ingress packets untagged and egress packets tagged |
When dhclient was started, it was the only one using the macvtap interface. But when dhclient was sending a packet in order to renew the lease after many hours, it broke macvtap because by that time the guest was also using the interface. And both host and guest cannot use the same interface simultanously.
If a totally different program had just sended a random packet over that interface from the host, for example a simple ping, the same would have happened. So this problem was not related to DHCP in any way.
|
I setup a macvtap interface like this:
ip link add link eth0 vlan type macvlan mode bridge
ip address add 10.0.0.17 dev vlan
ip link set dev vlan up
ip route flush dev eth0
ip route flush dev vlan
ip route add 10.0.0.0/24 dev vlan metric 0
ip route add default via 10.0.0.1
ip link add link eth0 name vtap address xx:xx:xx:xx:xx:xx type macvtap mode bridge
ip link set vtap up
ip address flush eth0
ip address flush vtap
dhclient -v vtap
ip address flush vtapAnd it works fine for a couple of hours. But after that, any connections to the DHCP (macvtap) IP will start going to the host machine instead. So if I connect to the IP at port 80 for example, I will see a page served by the host instead of the VM.
I am trying to understand why it stops working. At first I thought maybe the DHCP lease expired, and dhclient is not renewing it. But the leasetime is 24 hours, and this problem starts earlier than that, sometimes in less than 10 hours.
So what can be causing the macvtap interface to stop working?
| Macvtap connectivity lost after a few hours? |
I'll limit my references to IPv4 (IPv6 or ARP are also affected, but IPv6 isn't used by OP and no default firewall for ARP exists).
Docker relies on and loads the kernel module br_netfilter for proper control of container isolation, even between two containers in the same LAN.
This makes Netfilter call IPv4 hooks for bridged frames of type IPv4. While this is documented for iptables, nftables uses the same Netfilter API and its IPv4 hooks (thus family ip for pure IPv4 and family inet for hybrid IPv4+IPv6) are affected the same. The result is described with this schematic:With br_netfilter loaded, iptables and nftables IPv4 components (small green boxes) normally used in the IPv4 network layer (green boxes in green field) are also used for the bridging link layer case (green boxes in blue field).
So a bridged frame becomes firewalled by iptables's filter/FORWARD chain. And OP did something that's normally not needed (without br_netfilter bridged frames never traverse iptables' filter/FORWARD):sudo iptables -A FORWARD -i br0 -j ACCEPTThis allows to bypass the default DROP policy installed by Docker in the FORWARD chain and which now applies to bridged frames. Actually when Docker is around, this rule should be inserted (rather than added) to the DOCKER-USER chain instead with:
sudo iptables -I DOCKER-USER -i br0 -j ACCEPTBut it's also firewalled by any additional hook doing the same: here pure nftables installed by Firewalld, using the inet firewalld table. This part rejects the bridged packets:
table inet firewalld {... chain filter_FORWARD {
type filter hook forward priority filter + 10; policy accept;... reject with icmpx admin-prohibited
}In the end the packet is accepted in the first (iptables) forward hook, but gets rejected in the second (Firewalld's nftables) forward hook.
Here, simply doing (in addition to OP's iptables command) this as root user, using nftables:
nft insert rule inet firewalld filter_FORWARD iifname br0 oifname br0 acceptwill also allow the frame in this second hook until the rule gets overwritten. The setup should instead be added in Firewalld's own configuration.
Testing on a Fedora 37 container whith Firewalld changed to OP's settings (and module br_netfilter loaded on host), here's how to get Firewalld to add a forward accept rule for the br0 interface and the ping working:
firewall-cmd --zone=FedoraWorkstation --remove-interface=br0
firewall-cmd --zone=FedoraWorkstation --remove-interface=br0 --permanent
firewall-cmd --zone=trusted --add-interface=br0
firewall-cmd --zone=trusted --add-interface=br0 --permanentProbably some custom zone with adequate security rules should be used instead.
Some Stack Exchange links where I made answers to related Docker issues:
1 2 3 4
|
trying to make local networking experiment, and unable to ping from within the namespaced network.
I'm using Fedora 37.
Linux dmitry-desktop 6.1.18-200.fc37.x86_64 #1 SMP PREEMPT_DYNAMIC Sat Mar 11 16:09:14 UTC 2023 x86_64 x86_64 x86_64 GNU/LinuxI'm getting the following error
➜ sudo ip netns exec netns-test0 ping 10.10.10.11
PING 10.10.10.11 (10.10.10.11) 56(84) bytes of data.
From 10.10.10.1 icmp_seq=1 Packet filtered
From 10.10.10.1 icmp_seq=2 Packet filtered
From 10.10.10.1 icmp_seq=3 Packet filteredsetup
➜ sudo ip netns add netns-test0
➜ sudo ip netns add netns-test1
➜ ls -la /var/run/netns
total 0
drwxr-xr-x. 2 root root 80 Mar 22 13:42 .
drwxr-xr-x. 63 root root 1.7K Mar 22 12:55 ..
-r--r--r--. 1 root root 0 Mar 22 13:42 netns-test0
-r--r--r--. 1 root root 0 Mar 22 13:42 netns-test1➜ sudo ip link add eth00 type veth peer name eth01
➜ sudo ip link add eth10 type veth peer name eth11
➜ sudo ip link set eth00 up
➜ sudo ip link set eth01 up
➜ sudo ip link set eth01 netns netns-test0
➜ sudo ip link set eth11 netns netns-test1
➜ sudo ip netns exec netns-test0 ip link set lo up
➜ sudo ip netns exec netns-test0 ip link set eth01 up➜ sudo ip netns exec netns-test0 ip addr 10.10.10.10/24 dev eth01
Command "10.10.10.10/24" is unknown, try "ip address help".➜ sudo ip netns exec netns-test0 ip addr add 10.10.10.10/24 dev eth01
➜ sudo ip netns exec netns-test1 ip link set lo up
➜ sudo ip netns exec netns-test1 ip link set eth11 up
➜ sudo ip netns exec netns-test1 ip addr add 10.10.10.11/24 dev eth11
➜ sudo ip link add name br0 type bridge
➜ sudo ip addr add 10.10.10.1/24 brd + dev br0
➜ sudo ip link set br0 up ➜ sudo ip link set eth00 master br0
➜ sudo ip link set eth10 master br0➜ sudo bridge link show br0
20: eth00@if19: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master br0 state forwarding priority 32 cost 2
22: eth10@if21: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master br0 state forwarding priority 32 cost 2 ➜ sudo iptables -A FORWARD -i br0 -j ACCEPT
➜ sudo ip link set eth00 master br0so from the root namespace I can ping all devices and br0.
➜ ping 10.10.10.1
PING 10.10.10.1 (10.10.10.1) 56(84) bytes of data.
64 bytes from 10.10.10.1: icmp_seq=1 ttl=64 time=0.038 ms
64 bytes from 10.10.10.1: icmp_seq=2 ttl=64 time=0.057 ms➜ ping 10.10.10.10
PING 10.10.10.10 (10.10.10.10) 56(84) bytes of data.
64 bytes from 10.10.10.10: icmp_seq=1 ttl=64 time=0.047 ms
64 bytes from 10.10.10.10: icmp_seq=2 ttl=64 time=0.060 ms➜ ping 10.10.10.11
PING 10.10.10.11 (10.10.10.11) 56(84) bytes of data.
64 bytes from 10.10.10.11: icmp_seq=1 ttl=64 time=0.049 ms
64 bytes from 10.10.10.11: icmp_seq=2 ttl=64 time=0.053 msbut if I start pings from within the namespaced network - I get packet filtered.
➜ sudo ip netns exec netns-test0 ping 10.10.10.10
PING 10.10.10.10 (10.10.10.10) 56(84) bytes of data.
64 bytes from 10.10.10.10: icmp_seq=1 ttl=64 time=0.021 ms➜ sudo ip netns exec netns-test0 ping 10.10.10.1
PING 10.10.10.1 (10.10.10.1) 56(84) bytes of data.
64 bytes from 10.10.10.1: icmp_seq=1 ttl=64 time=0.063 ms
64 bytes from 10.10.10.1: icmp_seq=2 ttl=64 time=0.070 ms➜ sudo ip netns exec netns-test0 ping 10.10.10.11
PING 10.10.10.11 (10.10.10.11) 56(84) bytes of data.
From 10.10.10.1 icmp_seq=1 Packet filtered
From 10.10.10.1 icmp_seq=2 Packet filtered
From 10.10.10.1 icmp_seq=3 Packet filtered➜ sudo ip netns exec netns-test1 ping 10.10.10.11
PING 10.10.10.11 (10.10.10.11) 56(84) bytes of data.
64 bytes from 10.10.10.11: icmp_seq=1 ttl=64 time=0.018 ms
64 bytes from 10.10.10.11: icmp_seq=2 ttl=64 time=0.033 ms
64 bytes from 10.10.10.11: icmp_seq=3 ttl=64 time=0.036 ms➜ sudo ip netns exec netns-test1 ping 10.10.10.1
PING 10.10.10.1 (10.10.10.1) 56(84) bytes of data.
64 bytes from 10.10.10.1: icmp_seq=1 ttl=64 time=0.061 ms
64 bytes from 10.10.10.1: icmp_seq=2 ttl=64 time=0.075 ms
64 bytes from 10.10.10.1: icmp_seq=3 ttl=64 time=0.075 mstook 2s
➜ sudo ip netns exec netns-test1 ping 10.10.10.10
PING 10.10.10.10 (10.10.10.10) 56(84) bytes of data.
From 10.10.10.1 icmp_seq=1 Packet filtered
From 10.10.10.1 icmp_seq=2 Packet filtered
From 10.10.10.1 icmp_seq=3 Packet filtered
From 10.10.10.1 icmp_seq=4 Packet filteredtook 3s
✗ sudo ip netns exec netns-test1 ping 8.8.8.8
ping: connect: Network is unreachable➜ sudo ip netns exec netns-test0 ping 8.8.8.8
ping: connect: Network is unreachable➜ sudo ip -all netns exec ip route netns: netns-test1
10.10.10.0/24 dev eth11 proto kernel scope link src 10.10.10.11 netns: netns-test0
10.10.10.0/24 dev eth01 proto kernel scope link src 10.10.10.10 ➜ sudo ip -all netns exec ip route add default via 10.10.10.1netns: netns-test1
netns: netns-test0➜ sudo ip -all netns exec ip route netns: netns-test1
default via 10.10.10.1 dev eth11
10.10.10.0/24 dev eth11 proto kernel scope link src 10.10.10.11 netns: netns-test0
default via 10.10.10.1 dev eth01
10.10.10.0/24 dev eth01 proto kernel scope link src 10.10.10.10 ➜ sudo ip netns exec netns-test0 ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
From 10.10.10.1 icmp_seq=1 Packet filtered
From 10.10.10.1 icmp_seq=2 Packet filtered
From 10.10.10.1 icmp_seq=3 Packet filteredmy iptables config
➜ _ iptables -L -n -v
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination Chain FORWARD (policy DROP 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
95 7810 DOCKER-USER all -- * * 0.0.0.0/0 0.0.0.0/0
95 7810 DOCKER-ISOLATION-STAGE-1 all -- * * 0.0.0.0/0 0.0.0.0/0
13 1226 ACCEPT all -- * docker0 0.0.0.0/0 0.0.0.0/0 ctstate RELATED,ESTABLISHED
0 0 DOCKER all -- * docker0 0.0.0.0/0 0.0.0.0/0
15 956 ACCEPT all -- docker0 !docker0 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- docker0 docker0 0.0.0.0/0 0.0.0.0/0
67 5628 ACCEPT all -- br0 * 0.0.0.0/0 0.0.0.0/0
0 0 all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- br0 * 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- br0 * 0.0.0.0/0 0.0.0.0/0 Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination Chain DOCKER (1 references)
pkts bytes target prot opt in out source destination Chain DOCKER-ISOLATION-STAGE-1 (1 references)
pkts bytes target prot opt in out source destination
15 956 DOCKER-ISOLATION-STAGE-2 all -- docker0 !docker0 0.0.0.0/0 0.0.0.0/0
95 7810 RETURN all -- * * 0.0.0.0/0 0.0.0.0/0 Chain DOCKER-ISOLATION-STAGE-2 (1 references)
pkts bytes target prot opt in out source destination
0 0 DROP all -- * docker0 0.0.0.0/0 0.0.0.0/0
15 956 RETURN all -- * * 0.0.0.0/0 0.0.0.0/0 Chain DOCKER-USER (1 references)
pkts bytes target prot opt in out source destination
95 7810 RETURN all -- * * 0.0.0.0/0 0.0.0.0/0 firewalld:
➜ firewall-cmd --list-all
FedoraWorkstation (active)
target: default
icmp-block-inversion: no
interfaces: br0 ens1f1 eth01 eth11 vpn0
sources:
services: dhcpv6-client mdns samba-client ssh
ports: 1025-65535/udp 1025-65535/tcp
protocols:
forward: no
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:sudo nft list ruleset
table inet firewalld {
ct helper helper-netbios-ns-udp {
type "netbios-ns" protocol udp
l3proto ip
} chain mangle_PREROUTING {
type filter hook prerouting priority mangle + 10; policy accept;
jump mangle_PREROUTING_ZONES
} chain mangle_PREROUTING_POLICIES_pre {
jump mangle_PRE_policy_allow-host-ipv6
} chain mangle_PREROUTING_ZONES {
iifname "br0" goto mangle_PRE_FedoraWorkstation
iifname "eth11" goto mangle_PRE_FedoraWorkstation
iifname "eth01" goto mangle_PRE_FedoraWorkstation
iifname "vpn0" goto mangle_PRE_FedoraWorkstation
iifname "ens1f1" goto mangle_PRE_FedoraWorkstation
iifname "docker0" goto mangle_PRE_docker
goto mangle_PRE_FedoraWorkstation
} chain mangle_PREROUTING_POLICIES_post {
} chain nat_PREROUTING {
type nat hook prerouting priority dstnat + 10; policy accept;
jump nat_PREROUTING_ZONES
} chain nat_PREROUTING_POLICIES_pre {
jump nat_PRE_policy_allow-host-ipv6
} chain nat_PREROUTING_ZONES {
iifname "br0" goto nat_PRE_FedoraWorkstation
iifname "eth11" goto nat_PRE_FedoraWorkstation
iifname "eth01" goto nat_PRE_FedoraWorkstation
iifname "vpn0" goto nat_PRE_FedoraWorkstation
iifname "ens1f1" goto nat_PRE_FedoraWorkstation
iifname "docker0" goto nat_PRE_docker
goto nat_PRE_FedoraWorkstation
} chain nat_PREROUTING_POLICIES_post {
} chain nat_POSTROUTING {
type nat hook postrouting priority srcnat + 10; policy accept;
jump nat_POSTROUTING_ZONES
} chain nat_POSTROUTING_POLICIES_pre {
} chain nat_POSTROUTING_ZONES {
oifname "br0" goto nat_POST_FedoraWorkstation
oifname "eth11" goto nat_POST_FedoraWorkstation
oifname "eth01" goto nat_POST_FedoraWorkstation
oifname "vpn0" goto nat_POST_FedoraWorkstation
oifname "ens1f1" goto nat_POST_FedoraWorkstation
oifname "docker0" goto nat_POST_docker
goto nat_POST_FedoraWorkstation
} chain nat_POSTROUTING_POLICIES_post {
} chain nat_OUTPUT {
type nat hook output priority -90; policy accept;
jump nat_OUTPUT_POLICIES_pre
jump nat_OUTPUT_POLICIES_post
} chain nat_OUTPUT_POLICIES_pre {
} chain nat_OUTPUT_POLICIES_post {
} chain filter_PREROUTING {
type filter hook prerouting priority filter + 10; policy accept;
icmpv6 type { nd-router-advert, nd-neighbor-solicit } accept
meta nfproto ipv6 fib saddr . mark . iif oif missing drop
} chain filter_INPUT {
type filter hook input priority filter + 10; policy accept;
ct state { established, related } accept
ct status dnat accept
iifname "lo" accept
ct state invalid drop
jump filter_INPUT_ZONES
reject with icmpx admin-prohibited
} chain filter_FORWARD {
type filter hook forward priority filter + 10; policy accept;
ct state { established, related } accept
ct status dnat accept
iifname "lo" accept
ct state invalid drop
ip6 daddr { ::/96, ::ffff:0.0.0.0/96, 2002::/24, 2002:a00::/24, 2002:7f00::/24, 2002:a9fe::/32, 2002:ac10::/28, 2002:c0a8::/32, 2002:e000::/19 } reject with icmpv6 addr-unreachable
jump filter_FORWARD_ZONES
reject with icmpx admin-prohibited
} chain filter_OUTPUT {
type filter hook output priority filter + 10; policy accept;
ct state { established, related } accept
oifname "lo" accept
ip6 daddr { ::/96, ::ffff:0.0.0.0/96, 2002::/24, 2002:a00::/24, 2002:7f00::/24, 2002:a9fe::/32, 2002:ac10::/28, 2002:c0a8::/32, 2002:e000::/19 } reject with icmpv6 addr-unreachable
jump filter_OUTPUT_POLICIES_pre
jump filter_OUTPUT_POLICIES_post
} chain filter_INPUT_POLICIES_pre {
jump filter_IN_policy_allow-host-ipv6
} chain filter_INPUT_ZONES {
iifname "br0" goto filter_IN_FedoraWorkstation
iifname "eth11" goto filter_IN_FedoraWorkstation
iifname "eth01" goto filter_IN_FedoraWorkstation
iifname "vpn0" goto filter_IN_FedoraWorkstation
iifname "ens1f1" goto filter_IN_FedoraWorkstation
iifname "docker0" goto filter_IN_docker
goto filter_IN_FedoraWorkstation
} chain filter_INPUT_POLICIES_post {
} chain filter_FORWARD_POLICIES_pre {
} chain filter_FORWARD_ZONES {
iifname "br0" goto filter_FWD_FedoraWorkstation
iifname "eth11" goto filter_FWD_FedoraWorkstation
iifname "eth01" goto filter_FWD_FedoraWorkstation
iifname "vpn0" goto filter_FWD_FedoraWorkstation
iifname "ens1f1" goto filter_FWD_FedoraWorkstation
iifname "docker0" goto filter_FWD_docker
goto filter_FWD_FedoraWorkstation
} chain filter_FORWARD_POLICIES_post {
} chain filter_OUTPUT_POLICIES_pre {
} chain filter_OUTPUT_POLICIES_post {
} chain filter_IN_FedoraWorkstation {
jump filter_INPUT_POLICIES_pre
jump filter_IN_FedoraWorkstation_pre
jump filter_IN_FedoraWorkstation_log
jump filter_IN_FedoraWorkstation_deny
jump filter_IN_FedoraWorkstation_allow
jump filter_IN_FedoraWorkstation_post
jump filter_INPUT_POLICIES_post
meta l4proto { icmp, ipv6-icmp } accept
reject with icmpx admin-prohibited
} chain filter_IN_FedoraWorkstation_pre {
} chain filter_IN_FedoraWorkstation_log {
} chain filter_IN_FedoraWorkstation_deny {
} chain filter_IN_FedoraWorkstation_allow {
ip6 daddr fe80::/64 udp dport 546 ct state { new, untracked } accept
tcp dport 22 ct state { new, untracked } accept
udp dport 137 ct helper set "helper-netbios-ns-udp"
udp dport 137 ct state { new, untracked } accept
udp dport 138 ct state { new, untracked } accept
ip daddr 224.0.0.251 udp dport 5353 ct state { new, untracked } accept
ip6 daddr ff02::fb udp dport 5353 ct state { new, untracked } accept
udp dport 1025-65535 ct state { new, untracked } accept
tcp dport 1025-65535 ct state { new, untracked } accept
} chain filter_IN_FedoraWorkstation_post {
} chain nat_POST_FedoraWorkstation {
jump nat_POSTROUTING_POLICIES_pre
jump nat_POST_FedoraWorkstation_pre
jump nat_POST_FedoraWorkstation_log
jump nat_POST_FedoraWorkstation_deny
jump nat_POST_FedoraWorkstation_allow
jump nat_POST_FedoraWorkstation_post
jump nat_POSTROUTING_POLICIES_post
} chain nat_POST_FedoraWorkstation_pre {
} chain nat_POST_FedoraWorkstation_log {
} chain nat_POST_FedoraWorkstation_deny {
} chain nat_POST_FedoraWorkstation_allow {
} chain nat_POST_FedoraWorkstation_post {
} chain filter_FWD_FedoraWorkstation {
jump filter_FORWARD_POLICIES_pre
jump filter_FWD_FedoraWorkstation_pre
jump filter_FWD_FedoraWorkstation_log
jump filter_FWD_FedoraWorkstation_deny
jump filter_FWD_FedoraWorkstation_allow
jump filter_FWD_FedoraWorkstation_post
jump filter_FORWARD_POLICIES_post
reject with icmpx admin-prohibited
} chain filter_FWD_FedoraWorkstation_pre {
} chain filter_FWD_FedoraWorkstation_log {
} chain filter_FWD_FedoraWorkstation_deny {
} chain filter_FWD_FedoraWorkstation_allow {
} chain filter_FWD_FedoraWorkstation_post {
} chain nat_PRE_FedoraWorkstation {
jump nat_PREROUTING_POLICIES_pre
jump nat_PRE_FedoraWorkstation_pre
jump nat_PRE_FedoraWorkstation_log
jump nat_PRE_FedoraWorkstation_deny
jump nat_PRE_FedoraWorkstation_allow
jump nat_PRE_FedoraWorkstation_post
jump nat_PREROUTING_POLICIES_post
} chain nat_PRE_FedoraWorkstation_pre {
} chain nat_PRE_FedoraWorkstation_log {
} chain nat_PRE_FedoraWorkstation_deny {
} chain nat_PRE_FedoraWorkstation_allow {
} chain nat_PRE_FedoraWorkstation_post {
} chain mangle_PRE_FedoraWorkstation {
jump mangle_PREROUTING_POLICIES_pre
jump mangle_PRE_FedoraWorkstation_pre
jump mangle_PRE_FedoraWorkstation_log
jump mangle_PRE_FedoraWorkstation_deny
jump mangle_PRE_FedoraWorkstation_allow
jump mangle_PRE_FedoraWorkstation_post
jump mangle_PREROUTING_POLICIES_post
} chain mangle_PRE_FedoraWorkstation_pre {
} chain mangle_PRE_FedoraWorkstation_log {
} chain mangle_PRE_FedoraWorkstation_deny {
} chain mangle_PRE_FedoraWorkstation_allow {
} chain mangle_PRE_FedoraWorkstation_post {
} chain filter_IN_policy_allow-host-ipv6 {
jump filter_IN_policy_allow-host-ipv6_pre
jump filter_IN_policy_allow-host-ipv6_log
jump filter_IN_policy_allow-host-ipv6_deny
jump filter_IN_policy_allow-host-ipv6_allow
jump filter_IN_policy_allow-host-ipv6_post
} chain filter_IN_policy_allow-host-ipv6_pre {
} chain filter_IN_policy_allow-host-ipv6_log {
} chain filter_IN_policy_allow-host-ipv6_deny {
} chain filter_IN_policy_allow-host-ipv6_allow {
icmpv6 type nd-neighbor-advert accept
icmpv6 type nd-neighbor-solicit accept
icmpv6 type nd-router-advert accept
icmpv6 type nd-redirect accept
} chain filter_IN_policy_allow-host-ipv6_post {
} chain nat_PRE_policy_allow-host-ipv6 {
jump nat_PRE_policy_allow-host-ipv6_pre
jump nat_PRE_policy_allow-host-ipv6_log
jump nat_PRE_policy_allow-host-ipv6_deny
jump nat_PRE_policy_allow-host-ipv6_allow
jump nat_PRE_policy_allow-host-ipv6_post
} chain nat_PRE_policy_allow-host-ipv6_pre {
} chain nat_PRE_policy_allow-host-ipv6_log {
} chain nat_PRE_policy_allow-host-ipv6_deny {
} chain nat_PRE_policy_allow-host-ipv6_allow {
} chain nat_PRE_policy_allow-host-ipv6_post {
} chain mangle_PRE_policy_allow-host-ipv6 {
jump mangle_PRE_policy_allow-host-ipv6_pre
jump mangle_PRE_policy_allow-host-ipv6_log
jump mangle_PRE_policy_allow-host-ipv6_deny
jump mangle_PRE_policy_allow-host-ipv6_allow
jump mangle_PRE_policy_allow-host-ipv6_post
} chain mangle_PRE_policy_allow-host-ipv6_pre {
} chain mangle_PRE_policy_allow-host-ipv6_log {
} chain mangle_PRE_policy_allow-host-ipv6_deny {
} chain mangle_PRE_policy_allow-host-ipv6_allow {
} chain mangle_PRE_policy_allow-host-ipv6_post {
} chain filter_IN_docker {
jump filter_INPUT_POLICIES_pre
jump filter_IN_docker_pre
jump filter_IN_docker_log
jump filter_IN_docker_deny
jump filter_IN_docker_allow
jump filter_IN_docker_post
jump filter_INPUT_POLICIES_post
accept
} chain filter_IN_docker_pre {
} chain filter_IN_docker_log {
} chain filter_IN_docker_deny {
} chain filter_IN_docker_allow {
} chain filter_IN_docker_post {
} chain nat_POST_docker {
jump nat_POSTROUTING_POLICIES_pre
jump nat_POST_docker_pre
jump nat_POST_docker_log
jump nat_POST_docker_deny
jump nat_POST_docker_allow
jump nat_POST_docker_post
jump nat_POSTROUTING_POLICIES_post
} chain nat_POST_docker_pre {
} chain nat_POST_docker_log {
} chain nat_POST_docker_deny {
} chain nat_POST_docker_allow {
} chain nat_POST_docker_post {
} chain filter_FWD_docker {
jump filter_FORWARD_POLICIES_pre
jump filter_FWD_docker_pre
jump filter_FWD_docker_log
jump filter_FWD_docker_deny
jump filter_FWD_docker_allow
jump filter_FWD_docker_post
jump filter_FORWARD_POLICIES_post
accept
} chain filter_FWD_docker_pre {
} chain filter_FWD_docker_log {
} chain filter_FWD_docker_deny {
} chain filter_FWD_docker_allow {
oifname "docker0" accept
} chain filter_FWD_docker_post {
} chain nat_PRE_docker {
jump nat_PREROUTING_POLICIES_pre
jump nat_PRE_docker_pre
jump nat_PRE_docker_log
jump nat_PRE_docker_deny
jump nat_PRE_docker_allow
jump nat_PRE_docker_post
jump nat_PREROUTING_POLICIES_post
} chain nat_PRE_docker_pre {
} chain nat_PRE_docker_log {
} chain nat_PRE_docker_deny {
} chain nat_PRE_docker_allow {
} chain nat_PRE_docker_post {
} chain mangle_PRE_docker {
jump mangle_PREROUTING_POLICIES_pre
jump mangle_PRE_docker_pre
jump mangle_PRE_docker_log
jump mangle_PRE_docker_deny
jump mangle_PRE_docker_allow
jump mangle_PRE_docker_post
jump mangle_PREROUTING_POLICIES_post
} chain mangle_PRE_docker_pre {
} chain mangle_PRE_docker_log {
} chain mangle_PRE_docker_deny {
} chain mangle_PRE_docker_allow {
} chain mangle_PRE_docker_post {
}
}
table ip nat {
chain DOCKER {
iifname "docker0" counter packets 0 bytes 0 return
} chain POSTROUTING {
type nat hook postrouting priority srcnat; policy accept;
oifname != "docker0" ip saddr 172.17.0.0/16 counter packets 4 bytes 230 masquerade
} chain PREROUTING {
type nat hook prerouting priority dstnat; policy accept;
fib daddr type local counter packets 22340 bytes 10759965 jump DOCKER
} chain OUTPUT {
type nat hook output priority -100; policy accept;
ip daddr != 127.0.0.0/8 fib daddr type local counter packets 42 bytes 3674 jump DOCKER
}
}
table ip filter {
chain DOCKER {
} chain DOCKER-ISOLATION-STAGE-1 {
iifname "docker0" oifname != "docker0" counter packets 15 bytes 956 jump DOCKER-ISOLATION-STAGE-2
counter packets 98 bytes 8062 return
} chain DOCKER-ISOLATION-STAGE-2 {
oifname "docker0" counter packets 0 bytes 0 drop
counter packets 15 bytes 956 return
} chain FORWARD {
type filter hook forward priority filter; policy drop;
counter packets 98 bytes 8062 jump DOCKER-USER
counter packets 98 bytes 8062 jump DOCKER-ISOLATION-STAGE-1
oifname "docker0" ct state related,established counter packets 13 bytes 1226 accept
oifname "docker0" counter packets 0 bytes 0 jump DOCKER
iifname "docker0" oifname != "docker0" counter packets 15 bytes 956 accept
iifname "docker0" oifname "docker0" counter packets 0 bytes 0 accept
iifname "br0" counter packets 70 bytes 5880 accept
counter packets 0 bytes 0
counter packets 0 bytes 0
counter packets 0 bytes 0
counter packets 0 bytes 0
counter packets 0 bytes 0
counter packets 0 bytes 0
iifname "br0" counter packets 0 bytes 0 accept
iifname "br0" counter packets 0 bytes 0 accept
} chain DOCKER-USER {
counter packets 98 bytes 8062 return
}
}so I guess this is related somehow to ip filter below
➜ sudo nft list table ip filter
table ip filter {
chain DOCKER {
} chain DOCKER-ISOLATION-STAGE-1 {
iifname "docker0" oifname != "docker0" counter packets 15 bytes 956 jump DOCKER-ISOLATION-STAGE-2
counter packets 98 bytes 8062 return
} chain DOCKER-ISOLATION-STAGE-2 {
oifname "docker0" counter packets 0 bytes 0 drop
counter packets 15 bytes 956 return
} chain FORWARD {
type filter hook forward priority filter; policy drop;
counter packets 98 bytes 8062 jump DOCKER-USER
counter packets 98 bytes 8062 jump DOCKER-ISOLATION-STAGE-1
oifname "docker0" ct state related,established counter packets 13 bytes 1226 accept
oifname "docker0" counter packets 0 bytes 0 jump DOCKER
iifname "docker0" oifname != "docker0" counter packets 15 bytes 956 accept
iifname "docker0" oifname "docker0" counter packets 0 bytes 0 accept
iifname "br0" counter packets 70 bytes 5880 accept
counter packets 0 bytes 0
counter packets 0 bytes 0
counter packets 0 bytes 0
counter packets 0 bytes 0
counter packets 0 bytes 0
counter packets 0 bytes 0
iifname "br0" counter packets 0 bytes 0 accept
iifname "br0" counter packets 0 bytes 0 accept
} chain DOCKER-USER {
counter packets 98 bytes 8062 return
}
} | packets are filtered via bridge using namespaced network card |
To have routing tables be adequately selected by routing rules with an interface bound using SO_BINDTODEVICE, rules with the keyword oif should also be used:oif NAME
select the outgoing device to match. The outgoing interface is only
available for packets originating from local sockets that are bound to
a device.Else during initial lookup, when no source address is also specified, the lookup is using the default INADDR_ANY (aka 0.0.0.0/0) as source selector before figuring out the correct source IP address later (eg from hinted source or other algorithms). As no added routing rule will match INADDR_ANY all the additional tables are skipped and this will end up evaluating only with the main routing table with an additional filter by the bound device: no default route is defined and thus no adequate gateway is used, except for br0 which has the default route also in the main table.
So these commands should be added, each line in its respective /etc/sysconfig/network-scripts/rule-brX file (minus ip rule add ):
ip rule add oif br0 lookup 3
ip rule add oif br1 lookup 4
ip rule add oif br2 lookup 5
ip rule add oif br3 lookup 6so that the adequate routing table is looked up when binding to an interface, thus providing the correct gateway in each case.All the kernel evaluation can be verified with ip route get:ip route get
get a single route
this command gets a single route to a destination and prints its
contents exactly as the kernel sees it.Before the additional rulesbr0
Assuming that for the sake of symmetry there's also a routing table like this (but it doesn't really matter: the main routing table is good enough for br0):
default via 10.3.0.1 dev br0 table 3
10.3.0.0/16 dev br0 table 3 scope link src 10.3.15.22 # ip route get from 10.3.15.22 to 8.8.8.8
8.8.8.8 from 10.3.15.22 via 10.3.0.1 dev br0 table 3 uid 0
cache
# ip route get oif br0 to 8.8.8.8
8.8.8.8 via 10.3.0.1 dev br0 src 10.3.15.22 uid 0
cache In the 2nd case, when just binding to the interface without selecting a source address, the main table gets used, but that's still correct, because the main table also has the default route for br0: it worksbr1
# ip route get from 10.4.15.22 to 8.8.8.8
8.8.8.8 from 10.4.15.22 via 10.4.0.1 dev br1 table 4 uid 0
cache
# ip route get oif br1 to 8.8.8.8
8.8.8.8 dev br1 src 10.4.15.22 uid 0
cache In the 2nd case, as there's nothing defining a gateway in the main table, the route uses no gateway and because the interface is forced, it's assumed that 8.8.8.8 is directly connected (tcpdump would probably show ARP queries emitted about 8.8.8.8 if anything).
It doesn't work.After the additional rules for the bound interface casebr0
# ip route get oif br0 to 8.8.8.8
8.8.8.8 via 10.3.0.1 dev br0 table 3 src 10.3.15.22 uid 0
cache While the overall result is the same: it works, this time the additional table was used.br1
# ip route get oif br1 to 8.8.8.8
8.8.8.8 via 10.4.0.1 dev br1 table 4 src 10.4.15.22 uid 0
cache This time, the oif br1 selector selected routing table 4 which does define a proper default route with a proper gateway: it works.Note: A similar setup using L3 interfaces (eg: VPN interfaces like WireGuard or OpenVPN in tun mode) wouldn't require this, because L3 interfaces don't need any gateway (even if defined it's not used since there's no L2 layer below IP to resolve) and thus no specific route definition is needed for traffic to be emitted when binding to such L3 interface. Anyway it's still a good idea to use it too, especially if the routing table contains routing negations.
|
Running into an odd issue where pinging from a VLAN interface specifying the IP address works, but when specifying the interface name it does not.
This system is running Rocky Linux 8.5 (4.18.0-348.el8.0.2.x86_64). It has a single network interface plugged in which is set up with 4 bridge interfaces using the old style network-scripts (see scripts below).
When pinging out to 8.8.8.8 without specifying any interface/IP at all, everything works as expected. If I specify br0, all works as expected. If I specify br1, br2 or br3, I get no reply. If I specify the IP address associated with br1, etc, then it works as expected.
Ping output
# PING WORKS
$ ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=104 ms
^C
--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 104.224/104.224/104.224/0.000 ms# PING WORKS
$ ping -I br0 8.8.8.8
PING 8.8.8.8 (8.8.8.8) from 10.3.15.22 br0: 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=101 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=118 time=101 ms# PING FAILS
$ ping -I br1 8.8.8.8
PING 8.8.8.8 (8.8.8.8) from 10.4.15.22 br1: 56(84) bytes of data.
^C
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 2031ms# PING WORKS
$ ping -I 10.4.15.22 8.8.8.8
PING 8.8.8.8 (8.8.8.8) from 10.4.15.22 : 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=4.72 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=119 time=4.65 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=119 time=4.65 ms
^C
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2004ms
rtt min/avg/max/mdev = 4.645/4.672/4.721/0.065 msAs you can see from the ip addr output below, interface br1 has IP address 10.4.15.22. As well, it is set up to use routing table vlan4 and has the proper rules associated with it.
Output from ip addr show
# ip addr show
3: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9000 qdisc mq master br0 state UP group default qlen 1000
link/ether 00:25:90:8e:b4:98 brd ff:ff:ff:ff:ff:ff
6: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9000 qdisc noqueue state UP group default qlen 1000
link/ether 00:25:90:8e:b4:98 brd ff:ff:ff:ff:ff:ff
inet 10.3.15.22/16 brd 10.3.255.255 scope global br0
valid_lft forever preferred_lft forever
7: eno1.4@eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9000 qdisc noqueue master br1 state UP group default qlen 1000
link/ether 00:25:90:8e:b4:98 brd ff:ff:ff:ff:ff:ff
8: br1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9000 qdisc noqueue state UP group default qlen 1000
link/ether 00:25:90:8e:b4:98 brd ff:ff:ff:ff:ff:ff
inet 10.4.15.22/16 brd 10.4.255.255 scope global br1
valid_lft forever preferred_lft forever
9: eno1.5@eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9000 qdisc noqueue master br2 state UP group default qlen 1000
link/ether 00:25:90:8e:b4:98 brd ff:ff:ff:ff:ff:ff
10: br2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9000 qdisc noqueue state UP group default qlen 1000
link/ether 00:25:90:8e:b4:98 brd ff:ff:ff:ff:ff:ff
inet 10.5.15.22/16 brd 10.5.255.255 scope global br2
valid_lft forever preferred_lft forever
11: eno1.6@eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9000 qdisc noqueue master br3 state UP group default qlen 1000
link/ether 00:25:90:8e:b4:98 brd ff:ff:ff:ff:ff:ff
12: br3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9000 qdisc noqueue state UP group default qlen 1000
link/ether 00:25:90:8e:b4:98 brd ff:ff:ff:ff:ff:ff
inet 10.6.15.22/16 brd 10.6.255.255 scope global br3
valid_lft forever preferred_lft foreversysconfig/network-scripts
$ cat /etc/sysconfig/network-scripts/ifcfg-eno1
TYPE=Ethernet
BOOTPROTO=none
DEVICE=eno1
ONBOOT=yes
BRIDGE=br0
NM_CONTROLLED=no
MTU=9000$ cat /etc/sysconfig/network-scripts/ifcfg-eno1.4
DEVICE=eno1.4
BRIDGE=br1
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
NM_CONTROLLED=no
MTU=9000
VLAN=yes$ cat /etc/sysconfig/network-scripts/ifcfg-br0
DEVICE=br0
TYPE=Bridge
BOOTPROTO=static
IPADDR=10.3.15.22
GATEWAY=10.3.0.1
DNS1=10.3.0.1
NETMASK=255.255.0.0
ONBOOT=yes
NM_CONTROLLED=no
DEFROUTE=yes$ cat /etc/sysconfig/network-scripts/ifcfg-br1
DEVICE=br1
IPADDR=10.4.15.22
GATEWAY=10.4.0.1
DNS1=10.4.0.1
DEFROUTE=no
TYPE=Bridge
BOOTPROTO=static
NETMASK=255.255.0.0
ONBOOT=yes
NM_CONTROLLED=no$ cat /etc/sysconfig/network-scripts/route-br1
10.4.0.0/16 dev br1 src 10.4.15.22 table vlan4
default via 10.4.0.1 dev br1 table vlan4$ cat /etc/sysconfig/network-scripts/rule-br1
from 10.4.15.22/32 table vlan4
to 10.4.15.22/32 table vlan4/etc/iproute2/rt_tables
$ cat /etc/iproute2/rt_tables
3 vlan3
4 vlan4
5 vlan5
6 vlan6ip route and ip rule output
$ ip route show
default via 10.3.0.1 dev br0
10.3.0.0/16 dev br0 proto kernel scope link src 10.3.15.22
10.4.0.0/16 dev br1 proto kernel scope link src 10.4.15.22
10.5.0.0/16 dev br2 proto kernel scope link src 10.5.15.22
10.6.0.0/16 dev br3 proto kernel scope link src 10.6.15.22
169.254.0.0/16 dev br0 scope link metric 1006
169.254.0.0/16 dev br1 scope link metric 1008
169.254.0.0/16 dev br2 scope link metric 1010
169.254.0.0/16 dev br3 scope link metric 1012$ ip route show table vlan4
default via 10.4.0.1 dev br1
10.4.0.0/16 dev br1 scope link src 10.4.15.22$ ip rule
0: from all lookup local
32758: from all to 10.6.15.22 lookup vlan6
32759: from 10.6.15.22 lookup vlan6
32760: from all to 10.5.15.22 lookup vlan5
32761: from 10.5.15.22 lookup vlan5
32762: from all to 10.4.15.22 lookup vlan4
32763: from 10.4.15.22 lookup vlan4
32764: from all to 10.3.15.22 lookup vlan3
32765: from 10.3.15.22 lookup vlan3
32766: from all lookup main
32767: from all lookup default | Ping from vlan bridge interface fails when specifying interface name, specifying IP address works as expected |
The bridge self interface, which is the part of the bridge participating in routing, must also be put in the adequate VLAN.
To configure the bridge interface rather than one of its port, the additional keyword self is needed. The routing stack (at layer 3) handles IPv4 or IPv6 packets, so expects to receive frames of such type, not tagged frames. Hence VLAN ID 10 must be untagged when leaving the bridge (so the routing stack receive traffic) and this must be the Port VLAN ID, so traffic from the routing stack to the bridge gets tagged back. Only one VLAN can be linked to the routing stack this way.
This gives:
bridge vlan del dev br0 vid 1 self
bridge vlan add dev br0 vid 10 untagged pvid self |
I created VLAN-aware bridge with command and add relevant interfaces:
% ip link add br0 type bridge vlan_filtering 1
% ip link set dev eth0 master br0
...(and repeat this for eth1, eth2, eth3)
Now, I want the bridge ports to handle frames with multiple tags, and have the frames stripped off tags and delivered on port br0 where I have a listening daemon:
% bridge vlan del dev eth0 vid 1
% bridge vlan add dev eth0 vid 2-4094
...(and repeat this for eth1, eth2, eth3)
After all commands completed, bridge setup looks as follows:
% bridge -c vlan sh
port vlan ids
br0 1 PVID Egress Untaggedeth3 2-4094eth2 2-4094eth1 2-4094eth0 2-4094br1 1 PVID Egress UntaggedNow when I send ping from host behind eth0 interface to br0 (having IP 192.168.1.1), I see with tcpdump that eth0 is indeed receiving tagged frame (in my case ID is 10), however br0 does not receive anything. What am I missing?
| Linux bridge with trunk ports and self bridge port |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.