The Prophet ﷺ said, "When you come upon a shepherd, call out to him three times. If he answers you, well and good. Otherwise, drink without causing any damage. And when you come upon the wall of an orchard, call out to its owner three times. If he answers you, well and good. Otherwise, eat without causing any damage."
عن النبي ﷺ قال: إذا أتيت على راع فناد ثلاث مرات، فإن أجابك وإلا فاشرب في غير أن تفسد، وإذا أتيت على حائط بستان فناد صاحب البستان ثلاث مرات، فإن أجابك وإلا فكل في أن لا تفسد.
Ibn Majah narrated it (2300) - and this is his wording -, as did Ahmad (11159), and Ibn Hibban graded it sahih (5281), as did Hakim (4/132), all of them through Yazid bin Harun, who said, "Jareeri informed us, from Abu Nadra, from Abu Saeed," and he related the hadith. They added, "Hospitality is three days, and whatever is beyond that is charity." Hakim said, "Sahih according to the criterion of Muslim." I say, it is as he said, except that Jareeri, who is Saeed bin Iyas, became confused toward the end of his life. Yazid bin Harun narrated from him during his period of confusion, but Hammad bin Salama corroborated him, and Hammad had narrated from him before his confusion set in. Ahmad narrated it (11045) through this route, from Muammal bin Ismail, from him, from Jareeri with his chain of transmission, in a similar wording.