"And Balaam lifted up his eyes." When he saw that he could not curse them, he sought to harm them with an evil eye, and he began to gaze at them. "And he saw Israel dwelling according to their tribes" — that each and every tribe was dwelling according to its tribes by itself, that they were not all dwelling intermingled. "And the spirit of God was upon him." Even though he did not wish to go, so that the word would not come to him, the Holy One, blessed be He, caused His Shekhinah to rest upon him. And even though the Shekhinah does not rest upon the impure, yet because of the love of Israel, "and the spirit of God was upon him" — this is the holy spirit that fell into his mouth, and he spoke by the holy spirit all that he spoke.
Why the Spirit of God Rested on Balaam Despite His Impurity
Midrash Aggadah, Numbers 24:2
וישא בלעם את עיניו. כשראה שלא היה יכול לקללם, ביקש להזיקם בעין רעה, התחיל מסתכל בהם [וירא את ישראל שוכן לשבטיו. שהיה כל שבט ושבט שוכן לשבטיו לבד, שלא היו הכל שוכנים מעורבבים: ותהי עליו רוח אלהים. אעפ"י שלא רצה ללכת כדי שלא יבוא אליו הדברו הקב"ה השרה עליו שכינתו, ואעפ"י שאין השכינה שורה על הטמאים, אבל בשביל אהבתן של ישראל, ותהי עליו רוח אלהים, זה רוח הקדש שנפל בפיו ואמר ברוח הקדש כל ה שדבר: